Aggregate function in R using column index numbers rather than names

Viewed 247

I want to use the aggregate function in R using column index numbers to identify the data frame columns being aggregated, rather than column names.

Here's an example that works using column names:

df = data.frame(A = c("a", "a", "b", "b", "c", "c"), B = 1:3, C = 1:3, D = 1:3)
aggregate(cbind(B, C, D) ~ A, data = df, sum)

But rather than listing B, C and D within cbind, I want to instruct it to use columns 2:4.

2 Answers

We can just use . to specify the rest of the columns

aggregate(. ~ A, data = df, sum)
  A B C D
1 a 3 3 3
2 b 4 4 4
3 c 5 5 5

Or if we want position index specifically, subset the data and convert to matrix

aggregate(as.matrix(df[2:4]) ~ A, data = df, sum)
A B C D
1 a 3 3 3
2 b 4 4 4
3 c 5 5 5

Or using dplyr

library(dplyr)
df %>%
     group_by(A) %>%
     summarise(across(all_of(names(.)[2:4]), sum))

Another way using column numbers would be

aggregate(df[2:4], list(grp = df[[1]]), sum)
#Or using df$A
#aggregate(df[2:4], list(grp = df$A), sum)

#  grp B C D
#1   a 3 3 3
#2   b 4 4 4
#3   c 5 5 5
Related