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.
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
Asked: 2023-04-30 00:53:48 +0000
Seen: 9 times
Last updated: Apr 30 '23
What is the process for initializing Java UDFs in Spark?
What does the error message "Error detected while processing $/.config/nvim/init.lua" mean?
What are the components that explain the state of ECMAScript execution context specification?
Does GraphDB automatically eliminate duplicate triples?
It appears that Vitest is not effectively mimicking or simulating behavior.
How can OMNET++ be used to simulate M/M/c/c?
How can I use oversampling to address a problem?
What is the method to determine the most precise categorization of data using Self Organizing Map?