Summarise data.table when "by" grouping variables stored as vector of strings

Viewed 148

I am trying to summarise a datatable as part of a function. The grouping variable changes depending on user requirements/data. The grouping variables are entered as a vector of strings. How can I use this as a grouping variable? See code below

library(data.table)
test <- as.data.table(mtcars)

grouping_vars <- c("vs", "am")

#does what I would like
test[,.(counts = .N,
       mpg = mean(mpg),
       disp = median(disp)), by = .(vs,am)]

#throws error
test[,.(counts = .N,
       mpg = mean(mpg),
       disp = median(disp)), by = .(grouping_vars)]

#only gets the first variable
test[,.(counts = .N,
       mpg = mean(mpg),
       disp = median(disp)), by = .(get(grouping_vars))]
1 Answers

Instead of .(, here we can use c(

library(data.table)
test[,.(counts = .N,
    mpg = mean(mpg),
    disp = median(disp)), by = c(grouping_vars)]
#    vs am counts      mpg  disp
#1:  0  1      6 19.75000 160.0
#2:  1  1      7 28.37143  79.0
#3:  1  0      7 20.74286 167.6
#4:  0  0     12 15.05000 355.0
Related