How to make a user-defined function work nicely with pipes and group_by? Here is a simple function:
library(tidyverse)
fun_head <- function(df, column) {
column <- enquo(column)
df %>% select(!!column) %>% head(1)
}
The function works nicely with pipes and allows to filter by another column:
mtcars %>% filter(cyl == 4) %>% fun_head(mpg)
> mpg
1 22.8
However, the same pipe-work fails with group_by
mtcars %>% group_by(cyl) %>% fun_head(mpg)
Adding missing grouping variables: `cyl`
# A tibble: 1 x 2
# Groups: cyl [1]
cyl mpg
<dbl> <dbl>
1 6 21
Using "do" after group_by makes it work:
> mtcars %>% group_by(cyl) %>% do(fun_head(., mpg))
# A tibble: 3 x 2
# Groups: cyl [3]
cyl mpg
<dbl> <dbl>
1 4 22.8
2 6 21
3 8 18.7
How should the function be changed so that it works uniformly with filter and group_by without needing "do"?
Or quosures have nothing do with the question, and group_by just requires using "do" because the function in the example has multiple arguments?