Ask Your Question
3

What is the method for utilizing a vector containing column names as an input for dplyr::group_by()?

asked 2023-04-30 00:53:48 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-04-30 01:03:02 +0000

lakamha gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-04-30 00:53:48 +0000

Seen: 8 times

Last updated: Apr 30 '23