[r] Error: could not find function "%>%"

I'm running an example in R, going through the steps and everything is working so far except for this code produces an error:

 words <- dtm %>%
 as.matrix %>%
 colnames %>%
 (function(x) x[nchar(x) < 20])

Error: could not find function "%>%"

I don't understand what the benefit of using this special operator %>% is, and any feedback would be great.

This question is related to r dplyr magrittr

The answer is


One needs to install magrittr as follows

install.packages("magrittr")

Then, in one's script, don't forget to add on top

library(magrittr)

For the meaning of the operator %>% you might want to consider this question: What does %>% function mean in R?

Note that the same operator would also work with the library dplyr, as it imports from magrittr.

dplyr used to have a similar operator (%.%), which is now deprecated. Here we can read about the differences between %.% (deprecated operator from the library dplyr) and %>% (operator from magrittr, that is also available in dplyr)


the following can be used:

 install.packages("data.table")
 library(data.table)

On Windows: if you use %>% inside a %dopar% loop, you have to add a reference to load package dplyr (or magrittr, which dplyr loads).

Example:

plots <- foreach(myInput=iterators::iter(plotCount), .packages=c("RODBC", "dplyr")) %dopar%
{
    return(getPlot(myInput))
}

If you omit the .packages command, and use %do% instead to make it all run in a single process, then works fine. The reason is that it all runs in one process, so it doesn't need to specifically load new packages.


The benefit is that the output of previous function is used. You do not need to repeat where the data source comes from, for example.