4

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?

David Arenburg
  • 91,361
  • 17
  • 137
  • 196
Alby
  • 5,522
  • 7
  • 41
  • 51
  • 3
    Interestingly, `\`%test%\` <- function(x,y)\`%>%\`(x,y)` works. – Frank Nov 05 '15 at 21:55
  • 3
    It seems that `%>%` tests if the function matches "%>%" with `is_pipe` and in `%test%`<- `%>%` it does not. E.g. " `%myop%` = function(x, y) match.call(); `%myop2%` = `%myop%`; `%myop3%` = function(x, y) x %myop% y " and call each: `"lhs" %myop% "rhs"; "lhs" %myop2% "rhs"; "lhs" %myop3% "rhs"` – alexis_laz Nov 06 '15 at 00:05

1 Answers1

7

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.

eddi
  • 49,088
  • 6
  • 104
  • 155