Sepp Hauser
Sepp Hauser

Reputation: 15

R: How to summarize and group by variables as column names

I have a wide dataframe with about 200 columns and want to summarize it over various columns. I can not figure the syntax for this, I think it should work with .data$ and .env$ but I don't get it. Heres an example:

> library(dplyr)
> df = data.frame('A'= c('X','X','X','Y','Y'), 'B'= 1:5, 'C' = 6:10)
> df
  A B  C
1 X 1  6
2 X 2  7
3 X 3  8
4 Y 4  9
5 Y 5 10
> df %>% group_by(A) %>% summarise(sum(B), sum(C))
`summarise()` ungrouping output (override with `.groups` argument)
# A tibble: 2 x 3
  A     `sum(B)` `sum(C)`
  <chr>    <int>    <int>
1 X            6       21
2 Y            9       19

But I want to be able to do something like this:

columns_to_sum = c('B','C')
columns_to_group = c('A')
df %>% group_by(colums_to_group)%>% summarise(sum(columns_to_sum))

Upvotes: 1

Views: 1376

Answers (1)

akrun
akrun

Reputation: 887118

We can use across from the new version of dplyr

library(dplyr)
df %>%
    group_by(across(colums_to_group)) %>% 
    summarise(across(all_of(columns_to_sum), sum, na.rm = TRUE), .groups = 'drop')
# A tibble: 2 x 3
#  A         B     C
#  <chr> <int> <int>
#1 X         6    21
#2 Y         9    19

In the previous version, we could use group_by_at along with summarise_at

df %>%
    group_by_at(colums_to_group) %>%
    summarise_at(vars(columns_to_sum), sum, na.rm = TRUE)

Upvotes: 2

Related Questions