spacyr provides a convenient R wrapper around the Python spaCy package. It offers easy access to the following functionality of spaCy:

  • parsing texts into tokens or sentences;
  • lemmatizing tokens;
  • parsing dependencies (to identify the grammatical structure of the sentence); and
  • identifying, extracting, or consolidating token sequences that form named entities or noun phrases.

It also allows a user to request additional token-level attributes directly from spaCy.

spacyr also takes care of the installation of not only spaCy but also Python itself, in a self-contained miniconda or virtualenv environment, and can install additional language models or upgrade spaCy as new models and versions become available.

Finally, spacyr works seamlessly with the quanteda package, although such use is optional.

Starting a spacyr session

spacyr works through the reticulate package that allows R to harness the power of Python. To access the underlying Python functionality, spacyr must open a connection by being initialized within your R session.

We provide a function for this, spacy_initialize(), which attempts to make this process as painless as possible. When spaCy has been installed in a conda environment with spacy_install() (and see for detailed instructions on this setup), spacy_initialize() automatically detects it and initializes spaCy. If spaCy is installed in a normal environment (i.e. not in a condaenv or virtualenv), spacy_initialize() searches your system for Python executables, and testing which have spaCy installed.

For power users with a specialized setup of spaCy (i.e. users who have a conda environment already set up for spaCy), it is possible to specify which environment or python executable to be used through one of the following methods:

  1. condaenv argument: supplying the name of conda environment
  2. virtualenv argument: supplying the path to the python virtual environment
  3. python_executable argument: supplying the path to the python

Tokenizing and tagging texts

The spacy_parse() function is spacyr’s main workhorse. It calls spaCy both to tokenize and tag the texts. It provides two options for part of speech tagging, plus options to return word lemmas, recognize names entities or noun phrases recognition, and identify grammatical structures features by parsing syntactic dependencies. It returns a data.frame corresponding to the emerging text interchange format for token data.frames.

The tokenization approach taken by spaCy is inclusive: it includes all tokens without restrictions, including punctuation characters and symbols.


Two fields are available for part-of-speech tags. The pos field returned is the Universal tagset for parts-of-speech, a general scheme that most users will find serves their needs, and also that provides equivalencies across languages. spacyr also provides a more detailed tagset, defined in each spaCy language model. For English, this is the OntoNotes 5 version of the Penn Treebank tag set.

The Penn Treebank is specific to English parts of speech. For other language models, the detailed tagset will be based on a different scheme. In the German language model, for instance, the universal tagset (pos) remains the same, but the detailed tagset (tag) is based on the TIGER Treebank scheme. Full details are available from the spaCy models web page.

Direct parsing of texts is also possible, using spacy_tokenize(). The options are designed to match those in the tokens() function from the quanteda package. By default this returns a named list (where the document name is the list element name):

but it can also output a data.frame:

Extracting language properties from texts

Entity and noun phrase recognition

spacyr can extract entities, either named or “extended” from the output of spacy_parse().

“Extended” entities including entities such as dates, events, and cardinal or ordinal quantities.

One very useful feature is to use the consolidation functions to compound multi-word entities into single “tokens” (as they would in a language like German):

In a similar manner to named entity extraction, spacyr can extract or concatenate [noun phrases* (or noun chunks).

Just as with entities, noun phrases can also be consolidated into single “tokens”:

If a user’s only goal is entity or noun phrase extraction, then two functions make this easy without first parsing the entire text:

Using other language models

By default, spacyr loads an English language model. You also can load spaCy’s other language models or use one of the language models with alpha support by specifying the model option when calling spacy_initialize(). We have successfully tested following language models with spaCy version 2.0.18.

Language ModelName
German de
Spanish es
Portuguese pt
French fr
Italian it
Dutch nl

This is an example of parsing German texts.

## first finalize the spacy if it's loaded
spacy_initialize(model = "de")
## Python space is already attached.  If you want to switch to a different Python, please restart R.
## successfully initialized (spaCy Version: 2.0.10, language model: de)
## (python options: type = "condaenv", value = "spacy_condaenv")

txt_german <- c(R = "R ist eine freie Programmiersprache für statistische Berechnungen und Grafiken. Sie wurde von Statistikern für Anwender mit statistischen Aufgaben entwickelt.",
               python = "Python ist eine universelle, üblicherweise interpretierte höhere Programmiersprache. Sie will einen gut lesbaren, knappen Programmierstil fördern.")
results_german <- spacy_parse(txt_german, dependency = FALSE, lemma = FALSE, tag = TRUE)
##    doc_id sentence_id token_id              token   pos   tag entity
## 1       R           1        1                  R PROPN    NE       
## 2       R           1        2                ist   AUX VAFIN       
## 3       R           1        3               eine   DET   ART       
## 4       R           1        4              freie   ADJ  ADJA       
## 5       R           1        5 Programmiersprache  NOUN    NN       
## 6       R           1        6                für   ADP  APPR       
## 7       R           1        7       statistische   ADJ  ADJA       
## 8       R           1        8       Berechnungen  NOUN    NN       
## 9       R           1        9                und  CONJ   KON       
## 10      R           1       10           Grafiken  NOUN    NN       
## 11      R           1       11                  . PUNCT    $.       
## 12      R           2        1                Sie  PRON  PPER       
## 13      R           2        2              wurde   AUX VAFIN       
## 14      R           2        3                von   ADP  APPR       
## 15      R           2        4       Statistikern  NOUN    NN  LOC_B
## 16      R           2        5                für   ADP  APPR       
## 17      R           2        6           Anwender  NOUN    NN       
## 18      R           2        7                mit   ADP  APPR       
## 19      R           2        8      statistischen   ADJ  ADJA       
## 20      R           2        9           Aufgaben  NOUN    NN       
## 21      R           2       10         entwickelt  VERB  VVPP       
## 22      R           2       11                  . PUNCT    $.       
## 23 python           1        1             Python  NOUN    NN MISC_B
## 24 python           1        2                ist   AUX VAFIN       
## 25 python           1        3               eine   DET   ART       
## 26 python           1        4        universelle   ADJ  ADJA       
## 27 python           1        5                  , PUNCT    $,       
## 28 python           1        6      üblicherweise   ADV   ADV       
## 29 python           1        7     interpretierte   ADJ  ADJA       
## 30 python           1        8             höhere   ADJ  ADJA       
## 31 python           1        9 Programmiersprache  NOUN    NN       
## 32 python           1       10                  . PUNCT    $.       
## 33 python           2        1                Sie  PRON  PPER       
## 34 python           2        2               will  VERB VMFIN       
## 35 python           2        3              einen   DET   ART       
## 36 python           2        4                gut   ADJ  ADJD       
## 37 python           2        5           lesbaren   ADJ  ADJA       
## 38 python           2        6                  , PUNCT    $,       
## 39 python           2        7            knappen   ADJ  ADJA       
## 40 python           2        8    Programmierstil  NOUN    NN       
## 41 python           2        9            fördern  VERB VVFIN       
## 42 python           2       10                  . PUNCT    $.

Note that the additional language models must first be installed in spaCy. When spaCy has been installed through spacy_install(), installation of additional language models is very simple. For example, the German language model can be installed (spacy_download_langmodel('de')). In other environments, you can install the model by entering python -m spacy download de in the console.

Integrating spacyr with other text analysis packages

With quanteda

The outputs and formats of spacyr are designed to integrate directly with the quanteda package.

For instance, many of its functions operate directly on spacyr objects, such as a parsed text.

require(quanteda, warn.conflicts = FALSE, quietly = TRUE)
## [1] "d1" "d2"
## [1] 2
## d1 d2 
##  9  9
## d1 d2 
##  9  9

Conversion of tokens is easily performed, and the tokenizers in spacyr tend to be smarter than the purely syntactic pattern-based parsers used by quanteda.

The latter is useful for say, selecting only nouns, using “glob” pattern matching with quanteda’s tokens_select() function:

spacy_parse("The cat in the hat ate green eggs and ham.", pos = TRUE) %>%
    as.tokens(include_pos = "pos") %>%
    tokens_select(pattern = c("*/NOUN"))
## tokens from 1 document.
## text1 :
## [1] "cat/NOUN"  "hat/NOUN"  "eggs/NOUN" "ham/NOUN"

Direct conversion of just the spaCy-based tokens is also possible:

including for sentences, for which spaCy’s recognition is very smart:

This also works well with entity recognition, e.g.

Adherence to the “TIF” standard

spacyr’s output was designed to conform to the Text Interchange Format, a cooperatively agreed standard structure for text package objects in R, such as corpus and token objects. spacy_initialize() can take a TIF corpus data.frame or character object as a valid input. Moreover, the data.frames returned by spacy_parse() and entity_consolidate() conform to the TIF tokens standard for data.frame tokens objects. This will make it easier to use with any text analysis package for R that works with TIF standard objects.

Finishing a session

When spacy_initialize() is executed, a background process of spaCy is attached in python space. This can take up a significant size of memory especially when a larger language model is used (e.g. en_core_web_lg). When you do not need the connection to spaCy any longer, you can remove the spaCy object by calling the spacy_finalize() function.

By calling spacy_initialize() again, you can reattach the backend spaCy.