Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call several variables to group_by in dplyr

Tags:

r

dplyr

shiny

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.

like image 366
Wlademir Ribeiro Prates Avatar asked Dec 23 '22 07:12

Wlademir Ribeiro Prates


2 Answers

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)
)
like image 58
Edgar Avatar answered Dec 25 '22 21:12

Edgar


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)
    )
like image 45
Chaitu Avatar answered Dec 25 '22 20:12

Chaitu