Using %>% operator from dplyr without loading dplyr in R

If you have 'dplyr' installed but not loaded you can get a result with:

 dplyr::`%>%`   # Note the backticks, although quotes work as well.

That displays the code but at the bottom you will see that its environment is actually the NAMESPACE of 'magritter' which 'dplyr' imports. As the two other knowledgeable respondents point out there are a couple of ways to use it as a function although it cannot just be interposed between a lhs and a rhs argument unless you make a local copy that has the flanking "%"'s or call it with the functional parentheses. The R parser won't allow:

>  mtcars dplyr::"%>%" summary()
Error: unexpected symbol in " mtcars dplyr"

You can refer to any object with non-standard name by enclosing in backticks. This means you can do this:

`%>%` <- magrittr::`%>%`

This will define the %>% operator in your current environment. For example:

iris %>% head

  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

The easiest way would be to load the magrittr package, which only does piping, and is the original source of %>%. If you don't want to load any packages, you can still use %>%, but not in any really useful way (unless you define it in your environment as Andrie suggests). Using it with :: would go like this:

# standard use
mtcars %>% summary()
# :: use
magrittr::"%>%"(mtcars, summary())

You really lose any advantage of readability/not nesting with this method.

Since you say you're building a package, you should put magrittr in Imports, or even just us importsFrom and grab the "%>%" function. See here for more info.

Tags:

Operators

R

Dplyr