Issues passing multiple arguments to function

I am trying to pass multiple arguments to a function. I have looked at previous questions from here and from SO, but can't get it to work with what I am doing. Any advice?

library(gapminder) # dataset
library(dplyr)

# will be documenting in package, so would be good to have group_var in here rather than dots if possible
test <- function(dataset, group_var, mean_col){
  group_list <- rlang::enquos(group_var)
  
  dataset %>% 
    group_by(.dots = group_list) %>% 
    summarise(mean = mean({{mean_col}}))
}


test(gapminder, year, pop) # group by one variable (works)
test(gapminder, c(continent, year), pop) # group by two variables (does not work)

# one variable - desired output
gapminder %>% 
  group_by(year) %>% 
  summarise(mean = mean(pop))

# A tibble: 12 x 2
    year      mean
 * <int>     <dbl>
 1  1952 16950402.
 2  1957 18763413.
 3  1962 20421007.
 4  1967 22658298.
 5  1972 25189980.
 6  1977 27676379.
 7  1982 30207302.
 8  1987 33038573.
 9  1992 35990917.
10  1997 38839468.
11  2002 41457589.
12  2007 44021220.

# two variables - desired output
gapminder %>% 
  group_by(continent, year) %>% 
  summarise(mean = mean(pop))

# A tibble: 60 x 3
# Groups:   continent [5]
   continent  year      mean
   <fct>     <int>     <dbl>
 1 Africa     1952  4570010.
 2 Africa     1957  5093033.
 3 Africa     1962  5702247.
 4 Africa     1967  6447875.
 5 Africa     1972  7305376.
 6 Africa     1977  8328097.
 7 Africa     1982  9602857.
 8 Africa     1987 11054502.
 9 Africa     1992 12674645.
10 Africa     1997 14304480.

I worked out that (the arguments as strings) this works:

test <- function(dataset, group_var, mean_col){
  
  dataset %>% 
    group_by(.dots = group_var) %>% 
    summarise(mean = mean({{mean_col}}))
}

test(gapminder, "year", pop) 
test(gapminder, c("continent", "year"), pop) 

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.