Search code examples
rmagrittr

Why can't I use the explicit form instead of a magrittr pipe in a call to R's split function?


library(magrittr)

mtcars %>% split(.$cyl)

split(mtcars, .$cyl)

I'm confused as to why the second line works, but the third line doesn't.

I'm reading http://r4ds.had.co.nz/, which states

enter image description here (http://r4ds.had.co.nz/transform.html#combining-multiple-operations-with-the-pipe)

This suggests the second and third lines should be identical, but the third gives the error

Error in split.default(x = seq_len(nrow(x)), f = f, drop = drop, ...) : object '.' not found

I got the second line from http://r4ds.had.co.nz/iteration.html#shortcuts, but I don't remember an explanation of the dot in this code. The author writes:

Here I’ve used . as a pronoun: it refers to the current list element (in the same way that i referred to the current index in the for loop).

But I don't understand what it means for a list element to be "current" in this context.

Why does the third line give an error when the second line doesn't?


Solution

  • Dot has no special meaning to R. It is the %>% that interprets the dot.

    Expressed in the usual form of function calls it is running this:

    "%>%"(mtcars, split(.$cyl))
    

    and the rules that %>% uses to process its arguments are defined in its help file:

    help("%>%", "magrittr")