We can use aggregate
from base R
. Use the formula method, specify the columns to sum
as a matrix
on the lhs of ~
and .
represents all the other columns used as grouping. Specify the aggregating function - sum
aggregate(cbind(attempts, yards) ~ ., df1, sum)
-output
firstname lastname season weight attempts yards
1 bob smith 2018 200 43 206
Or in tidyverse
, group across
columns other than 'attempts', 'yards', and summarise
across
all other (everything()
) and get the sum
library(dplyr)
df1 %>%
group_by(across(-c(attempts, yards))) %>%
summarise(across(everything(), sum), .groups = 'drop') %>%
select(names(df1))
-outupt
# A tibble: 1 x 6
firstname lastname season attempts yards weight
<chr> <chr> <int> <int> <int> <int>
1 bob smith 2018 43 206 200
data
df1 <- structure(list(firstname = c("bob", "bob", "bob", "bob"),
lastname = c("smith",
"smith", "smith", "smith"), season = c(2018L, 2018L, 2018L, 2018L
), attempts = c(7L, 11L, 17L, 8L), yards = c(38L, 56L, 88L, 24L
), weight = c(200L, 200L, 200L, 200L)), class = "data.frame", row.names = c(NA,
-4L))