[R] Pipe precedence

Duncan Murdoch murdoch@dunc@n @end|ng |rom gm@||@com
Sun May 23 11:34:27 CEST 2021


On 22/05/2021 8:26 p.m., Jeff Newmiller wrote:
> What is the precedence of the new |> pipe operator? I don't see it mentioned in ?Syntax, nor does it come up when I search the R Language Definition document.
> 

It's the same precedence as the %any% operators listed in the ?Syntax 
table, so it matches the magrittr pipe priority.  You can see this in 
the source if you know how to read Bison, or determine it experimentally:

 > 2 * 3 |> print()
[1] 3
[1] 6

This is the same result as

2 * ( 3 |> print() )

so it has higher priority than * .

On the other hand,

 > 2 : 3 |> print()
[1] 2 3

is the same as

( 2 : 3 ) |> print()

so it has lower priority than : .

A difference with the magrittr operator is in debugging.  If an error 
happens in the middle of a pipe, I find the traceback a little easier to 
understand with the built-in pipe:

 > 2 |> print() |> stop() |> mean()
[1] 2
Error in mean(stop(print(2))) : 2
 > traceback()
2: stop(print(2))
1: mean(stop(print(2)))

versus

 > 2 %>% print() %>% stop() %>% mean()
[1] 2
Error in mean(.) : 2
 > traceback()
3: stop(.)
2: mean(.)
1: 2 %>% print() %>% stop() %>% mean()

Duncan Murdoch



More information about the R-help mailing list