Why can't we use . as a parameter in an anonymous function with %>%
dplyr, plyr, r
Solution
The `.` ("the dot") has multiple uses, one of which is indeed as an argument. How it's actually interpreted is highly dependent on its context -- and in your context, it's used immediately before a `%>%` forward-pipe operator. `dplyr` takes its forward-pipe operator from `magrittr`, and from the `magrittr` documentation we have the following snippet on what happens when there's a `. %>% somefunction()`:
When the dot is used as lhs, the result will be a functional sequence, i.e. a function which applies the entire chain of right-hand sides in turn to its input.
So it's almost like an order of operations thing - a `%>%` immediately after the dot would interpret the dot as a part of the functional sequence.
One way to get your `.` understood as an argument instead is to add brackets around it, i.e.
llply(ll, function(.) (.) %>% group_by(cyl) %>% summarise(min = min(mpg)))
For a more thorough explanation of the different uses of `.` and `%>%`, and their interaction with each other, have a look at https://cran.r-project.org/web/packages/magrittr/magrittr.pdf. The relevant section starts from page 8.
Problem
Can somebody explain to me why the two following instructions have different outputs: ``` library(plyr) library(dplyr) ll <- list(a = mtcars, b = mtcars) # using '.' as a function parameter llply(ll, function(.) . %>% group_by(cyl) %>% summarise(min = min(mpg))) # using 'd' as function parameter llply(ll, function(d) d %>% group_by(cyl) %>% summarise(min = min(mpg))) ``` The former case is apparently not even evaluated (which I figured by misspelling `summarise`: `llply(ll, function(.) . %>% group_by(cyl) %>% sumamrise(min = min(mpg)))` would not throw an error). So this has all to do with scoping rules and where things are evaluated, but I really want to understand what is going on, and why this happens? I use `.` as an argument in anonymous functions quite often and I was puzzled to see the outcome. So long story short, why does `.` not work with `%>%`?