Stefano Stefano - 1 year ago 74
R Question

R - group data frame from a variable

I want to set the column for grouping a data frame into a variable and then group and summarise the data frame based on it, i.e.

var <- colnames(mtcars)[10]
summaries <- mtcars %>% dplyr::group_by(var) %>% dplyr::summarise_each(funs(mean))

such that I can simply change
and use the second line without changing anything. Unfortunately my solution does not work as
asks the column name and not a variable.

Answer Source

Use group_by_, which takes arguments as character strings:

var <- colnames(mtcars)[10]
summaries <- mtcars %>% dplyr::group_by_(var) %>% dplyr::summarise_each(funs(mean))

(Maybe resources on standard vs non-standard evaluation would be of interest:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download