Мы можем использовать diff
в «Всего» после группировки по «Коду» и «Сезону»
aggregate(cbind(Change = Total) ~ Code + Season, df1, diff)
Или с dplyr
library(dplyr)
df1 %>%
group_by(Code, Season) %>%
summarise(Change = Total[Event == "Pre"] - Total[Event == "Post"])
# A tibble: 3 x 3
# Groups: Code [2]
# Code Season Change
# <chr> <chr> <int>
#1 A AUTUMN 3
#2 A SUMMER -25
#3 B AUTUMN -3
Или используя data.table
library(data.table)
setDT(df1)[, .(Change = Total[Event == 'Pre'] - Total[Event == 'Post']), .(Code, Season)]
data
df1 <- structure(list(Code = c("A", "A", "A", "A", "B", "B"), Event = c("Post",
"Pre", "Pre", "Post", "Pre", "Post"), Season = c("AUTUMN", "AUTUMN",
"SUMMER", "SUMMER", "AUTUMN", "AUTUMN"), Total = c(2L, 5L, 15L,
40L, 5L, 8L)), class = "data.frame", row.names = c(NA, -6L))