alfakini alfakini - 1 month ago 15
R Question

What does %>% function mean in R?

I have seen the use of

%>%
(percent greater than percent) function in some packages like dplyr and rvest. What does it mean? Is it a way to write closure blocks in R?

Thanks

Answer

%...% operators. %>% has no builtin meaning but the user (or a package) is free to define operators of the form %whatever% in any way they like. For example, this function will return a string consisting of its left argument followed by a comma and then it's right argument.

"%,%" <- function(x, y) paste(x, y, sep = ",")

# test run

"Hello" %,% "World"
## [1] "Hello,World"

The base of R provides %*% (matrix mulitiplication), %/% (integer division), %in% (is lhs a component of the rhs?), %o% (outer product) and %x% (kronecker product). It is not clear whether %% falls in this category or not but it represents modulo.

magrittr In the case of %>% the magrittr R package has defined it as discussed in the magrittr vignette. See http://cran.r-project.org/web/packages/magrittr/vignettes/magrittr.html David Arenburg also provided this link in the comments: http://rpackages.ianhowson.com/cran/magrittr/man/pipe.html

magittr has also defined a number of other such operators too. See: http://cran.r-project.org/web/packages/magrittr/magrittr.pdf

dplyr The dplyr R package used to define a %.% operator which is similar; however, it has been deprecated and dplyr now recommends that users use %>% which dplyr imports from magrittr and makes available to the dplyr user. As David Arenburg has mentioned in the comments this SO question discusses the differences between it and magrittr's %>% : Differences between %.% (dplyr) and %>% (magrittr)

pipeR The R package, pipeR, defines a %>>% operator that is similar to magrittr's %>% . See http://renkun.me/pipeR-tutorial/

The pipeR package also has defined a number of other such operators too. See: http://cran.r-project.org/web/packages/pipeR/pipeR.pdf

expm The R package, expm, defines a matrix power operator %^%. For an example see Matrix power in R .

operators The operators R package has defined a large number of such operators such as %!in% (for not %in%). See http://cran.r-project.org/web/packages/operators/operators.pdf

Update Added info on expm package and simplified example at top.

Comments