Differences between %.% (dplyr) and %>% (magrittr)
Asked Answered
J

2

24

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.

Jessie answered 13/5, 2014 at 0:53 Comment(1)
Update: possible answers lurking in the comments here: blog.rstudio.org/2014/01/17/introducing-dplyrJessie
M
16

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
    
Millicentmillie answered 18/5, 2014 at 14:58 Comment(0)
W
36

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

Wormseed answered 13/5, 2014 at 0:58 Comment(3)
but now I can see this info and (maybe?) not incur the rtfm "penalty" ?Nessy
SOF is a better vehicle for fuzzy ("I don't even know what exactly the term is for that concept..") documentation searchingNessy
I would say this should be the new accepted answer because the other one is more or less obsolete at this point.Cheerly
M
16

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
    
Millicentmillie answered 18/5, 2014 at 14:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.