Basil
Basil

Reputation: 1004

How to group by using a variable in R

I can do a group_by by naming the column, but when I put that column name into a variable, it gives the error message Error: Must group by variables found in .data. Column grouping is not found.

How can I get R to recognise use the variable to use in group_by ?

library(tidyverse)

iris%>%group_by(Species)

grouping<-"Species"

iris%>%group_by(grouping)

Upvotes: 3

Views: 812

Answers (1)

akrun
akrun

Reputation: 886938

Either use across with all_of

library(dplyr)
iris %>%
    group_by(across(all_of(grouping)))

Or convert to symbol and evaluate

iris %>%
    group_by(!! rlang::sym(grouping))

Or with .data

iris %>%
    group_by(.data[[grouping]])

Upvotes: 3

Related Questions