Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between %.% (dplyr) and %>% (magrittr)

Tags:

The dplyr package introduced the %.% operator to pass the left hand side as an argument of the function on the right hand side, similar to a *NIX pipe. The magrittr package is a much more lightweight package that exists to define only that pipe-like operator.

Yet one uses %.% and the other %>%.

Is there any difference between the two? Can I just use %>% even in dplyr code, or will that cause subtle bugs?

On inspecting the code, they take very different paths early on, so simple eyeball comparison would suggest that they're different. I haven't been able to find anything documented when I search the web for them, nor have I run across anything in the documentation itself.

like image 724
Ari B. Friedman Avatar asked May 13 '14 00:05

Ari B. Friedman


People also ask

What does %>% do in R?

1 Answer. %>% is called the forward pipe operator in R. It provides a mechanism for chaining commands with a new forward-pipe operator, %>%. This operator will forward a value, or the result of an expression, into the next function call/expression.

What is Magrittr pipe?

To achieve its humble aims, magrittr (remember the accent) provides a new “pipe”-like operator, %>% , with which you may pipe a value forward into an expression or function call; something along the lines of x %>% f , rather than f(x) .

Is Magrittr part of the Tidyverse?

magrittr is the package home to the %>% pipe operator written by Stefan Milton Bache and used throughout the tidyverse.

What is Magrittr package?

Overview. The magrittr package offers a set of operators which make your code more readable by: structuring sequences of data operations left-to-right (as opposed to from the inside and out), avoiding nested function calls, minimizing the need for local variables and function definitions, and.


2 Answers

See the very first item in the current NEWS file:

dplyr now imports %>% from magrittr (#330). I recommend that you use this instead of %.% because it is easier to type (since you can hold down the shift key) and is more flexible

like image 97
Dirk Eddelbuettel Avatar answered Sep 27 '22 15:09

Dirk Eddelbuettel


dplyr now imports %>% from magrittr and uses it by default. See this answer for details.


Differences include

  • you can use a . as placeholder for the left-hand side, e.g.

     iris %>% plot(Sepal.Length ~ Sepal.Width, data = .) 
  • %>% respects (rhs), e.g.

     1:10 %>% (call("sum"))  1:10 %>% (function(x) x^2 + 2*x)  

    For a more useful example of this, see
    https://gist.github.com/anonymous/0c69b019d0b4f6ae5050

  • For single argument function calls, you can omit parens:

     "2014-05-18" %>% as.Date 
like image 25
Stefan Avatar answered Sep 27 '22 16:09

Stefan