1

I would write a function for a data processing such as:

get_df <- function(data, by = 'cyl', summ = c('disc', hb)){
         data %>% group_by(by)%>%
            summarise(disp = mean(summ[1]),
                        hp = mean(summ[2]))
}

How to make get_df(mtcars, by='cyl', summ = c('disp', 'hp')) functioning as

mtcars %>% group_by(cyl)%>%
summarise(
  disp = mean(disp),
  hp = mean(hp)
)
David Z
  • 6,641
  • 11
  • 50
  • 101

1 Answers1

3

If the function arguments are string for by and summ, then an option is to use across with all_of in both group_by and summarise

get_df <- function(data, by = 'cyl', summ = c('disp', 'hp')){
     data %>% 
     group_by(across(all_of(by))) %>%
     summarise(across(all_of(summ), mean), .groups = 'drop')
  }

-output

get_df(mtcars)
# A tibble: 3 x 3
#    cyl  disp    hp
#* <dbl> <dbl> <dbl>
#1     4  105.  82.6
#2     6  183. 122. 
#3     8  353. 209. 
akrun
  • 874,273
  • 37
  • 540
  • 662