我有以下数据:
df1 <- data.frame(Observation=c("A", "B", "B", "B", "C", "C", "C"),
Type=c(1,2,2,1,1,1,2), Value= c(1.5,1,3,2.1,3,4,6))
我想将具有相同数据类型(1或2)的每个Observation的行相加,所以它看起来像这样:
df2 <- data.frame (Observation=c("A", "B", "B", "C", "C"),
Type=c(1,2,1,1,2), Value= c(1.5,4,2.1,7,6))
我已经彻底查看了相关问题但却无法解决问题。
答案 0 :(得分:2)
尝试data.table
library(data.table)
setDT(df1)[, list(Value=sum(Value, na.rm=TRUE)), by=list(Observation, Type)]
# Observation Type Value
#1: A 1 1.5
#2: B 2 4.0
#3: B 1 2.1
#4: C 1 7.0
#5: C 2 6.0
答案 1 :(得分:1)
> aggregate(Value~Type+Observation,df1,sum)
Type Observation Value
1 1 A 1.5
2 1 B 2.1
3 2 B 4.0
4 1 C 7.0
5 2 C 6.0
答案 2 :(得分:1)
dplyr
的解决方案:
library(dplyr)
df1 %>%
group_by(Observation, Type) %>%
summarise(Value = sum(Value))