Как насчет этого?
library(dplyr)
df1 <- df %>%
group_by(Key, Date) %>%
mutate(Value = sum(Value),
Name = ifelse(n() > 1, 'SUM', Name), #identify rows where 'SUM' is applied and replace Name & type column with 'SUM'
Type = ifelse(n() > 1, 'SUM', Type)) %>%
filter(row_number() == 1)
df1
Вывод:
Key Date Value Name Type Year
1 C 2000-04 1.15 SUM SUM 2000
2 C 2000-05 1.20 Name4 x4 2000
3 A 2001-06 4.00 Name2 x6 2001
4 A 2001-07 5.00 Name3 x1 2001
5 A 2002-08 2.00 Name1 x2 2002
Пример данных:
df <- structure(list(Key = c("C", "C", "C", "A", "A", "A"), Date = c("2000-04",
"2000-04", "2000-05", "2001-06", "2001-07", "2002-08"), Value = c(0.55,
0.6, 1.2, 4, 5, 2), Name = c("name1", "name2", "Name4", "Name2",
"Name3", "Name1"), Type = c("x1", "x2", "x4", "x6", "x1", "x2"
), Year = c(2000L, 2000L, 2000L, 2001L, 2001L, 2002L)), .Names = c("Key",
"Date", "Value", "Name", "Type", "Year"), class = "data.frame", row.names = c(NA,
-6L))