Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you efficiently group by multiple columns in dplyr

With dplyr you can group by columns like this:

library(dplyr)

df <- data.frame(a=c(1,2,1,3,1,4,1,5), b=c(2,3,4,1,2,3,4,5))
df %>%
  group_by(a) %>%
  summarise(count = n())

If I want to group by two columns all the guides say:

df %>%
  group_by(a,b) %>%
  summarise(count = n())

But can I not feed the group_by() parameters more efficiently somehow, rather than having to type them in explicitly, e.g. like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

cols = colnames(df)
df %>%
  group_by(cols) %>%
  summarise(count = n())

I have examples where I want to group by 10+ columns, and it is pretty horrible to write it out if you can just parse their names.

>Solution :

across and curly-curly is the answer (even though it doesn’t make sense to group_by using all your columns)

cols = colnames(df)
df %>%
  group_by(across({{cols}}) %>%
  summarise(count = n())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading