Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the following code trying to alias %>% from magrittr symbol fail?

Tags:

r

magrittr

Why does the following code not work?

require(dplyr)
`%test%`<- `%>%`
mtcars %test% head
#Error in pipes[[i]] : subscript out of bounds

When the following works?

a <- function(x) x^2
a(4)
#[1] 16
b <- a
b(4)
#[1] 16

Why does this happen, and what needs to be done to make it work?

like image 889
Alby Avatar asked Mar 15 '23 06:03

Alby


1 Answers

As alexis_laz points out above it has to do with magrittr:::is_pipe explicitly checking for %>% in your expression and not finding it and subsequent logic falling apart in %>% because of that.

But why does %>% need to explicitly look for (self or other) %>% in the call?

If you look at the source code - the first %>% actually expands the full call and constructs the expression that doesn't have any more pipes and eval's that expression. So the actual %>% operator only gets called once in a pipe, and a %>% b %>% c is converted in that first call directly to c(b(a)) which then gets eval'd (as opposed to being converted first to b(a) %>% c).

It's not obvious to me that this has efficiency savings, so could be something more basic like keeping track of the . more easily when doing everything at once.

like image 77
eddi Avatar answered Apr 25 '23 11:04

eddi