To utilize a vector containing column names as an input for dplyr::group_by(), you can use the {{ }} curly-curly syntax for non-standard evaluation (NSE) along with the !! bang-bang operator to interpolate the variable.
For example, if your vector containing column names is called "vars", you can use the following code:
library(dplyr)
vars <- c("col1", "col2", "col3")
df %>%
group_by({{vars}})
The curly-curly syntax {{ }} tells R to evaluate the expression inside the braces as a variable name rather than as a character string, while the bang-bang operator !! tells R to interpolate the variable.
Note that you can also use the standard evaluation syntax by converting your vector to a list using the function as.list(), as follows:
vars <- c("col1", "col2", "col3")
df %>%
group_by_at(vars = as.list(vars))
The function groupbyat() allows you to specify the columns to group by using a character vector of column names, a numeric vector of column positions, or a list of column specifications.
Asked: 2023-04-30 00:53:48 +0000
Seen: 8 times
Last updated: Apr 30 '23