Hey there!
If you look closely, you can see that in the one-column example and in your mapped example, your present cyl in different ways. The first time as an object using dplyr-like non-standard evaluation. The second time, however, as a character. That's the problem right there. If you run
mtcars %>%
sum_n("cyl")
you wont get the same output as before.
We can change your original function to accept column names as characters by using across() in the group_by():
sum_n <- function(df, x) {
df %>%
group_by(across(x)) %>%
summarise(n = n())
}
Now if we run your mapped example it works as expected:
sum_vars <- c("cyl", "am", "gear")
purrr::map(sum_vars, ~sum_n(mtcars, .x))
across() is very useful, especially in combination with tidyr-selector functions, as you can dynamically do something to multiple columns as well. You can also use it in summarise() for example to get the median of your sum_vars So it's worth checking out.
mtcars %>%
summarise(
across(
any_of(sum_vars),
median)
)
One last note: also check out group_map that can apply functions to each group of a data.frame and group_modify.
Hope this helps.
Best,
Valentin