Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass column names as strings to group_by and summarize

With dplyr starting version 0.7 the methods ending with underscore such as summarize_ group_by_ are deprecated since we are supposed to use quosures.

See: https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html

I am trying to implement the following example using quo and !!

Working example:

df <- data.frame(x = c("a","a","a","b","b","b"), y=c(1,1,2,2,3,3), z = 1:6)

lFG <- df %>% 
   group_by( x,y) 
lFG %>% summarize( min(z))

However, in the case, I need to implement the columns to group by and summarize are specified as strings.

cols2group <- c("x","y")
col2summarize <- "z"

How can I get the same example as above working?

like image 210
witek Avatar asked Oct 24 '17 19:10

witek


1 Answers

From dplyr 1.0.0 you can use across :

library(dplyr)

cols2group <- c("x","y")
col2summarize <- "z"

df %>%
  group_by(across(all_of(cols2group))) %>%
  summarise(across(all_of(col2summarize), min)) %>%
  ungroup

#   x       y     z
#  <chr> <dbl> <int>
#1 a         1     1
#2 a         2     3
#3 b         2     4
#4 b         3     5
like image 164
Ronak Shah Avatar answered Oct 09 '22 03:10

Ronak Shah