How to call several variables to group_by in dplyr

I am trying to use group_by and summarise with several columns, which will be interactive in a shiny app. So, if I specify the column names inside group_by function it works, but if I create a vector for column names, so it does not work anymore. Here follows an example with Iris dataset:

# Working
iris %>% group_by(Sepal.Length, Species) %>% 
  summarise(
    `Sum.Sepal.Width` = sum(Sepal.Width)
  )

# Not working
columns <- c("Sepal.Length", "Species")
iris %>% group_by(columns) %>% 
  summarise(
    `Sum.Sepal.Width` = sum(Sepal.Width)
  )

Thanks. Wlademir.

Upvotes: 4

Views: 301

Answers (3)

Edgar
Edgar

Reputation: 256

As mentioned in this question, it should work by using group_by_at():

columns <- c("Sepal.Length", "Species")
iris %>% group_by_at(columns) %>% 
  summarise(
    "Sum.Sepal.Width" = sum(Sepal.Width)
)

Upvotes: 4

Aur&#232;le
Aur&#232;le

Reputation: 12819

Yet another method is to use rlang::syms:

iris %>% 
  group_by(!!! rlang::syms(columns)) %>% 
  summarise(
    `Sum.Sepal.Width` = sum(Sepal.Width)
  )

Upvotes: 3

Chaitu
Chaitu

Reputation: 151

Error in grouped_df_impl(data, unname(vars), drop) :

  columns <- c("Sepal.Length", "Species")

  iris %>% group_by(.dots = columns) %>% 
    summarise(
      `Sum.Sepal.Width` = sum(Sepal.Width)
    )

Upvotes: 3

Related Questions