我正在 R 中使用两个不同的三列表,例如:
Initial Final Changes
1 1 200
1 3 500
3 1 250
3 3 175
Table 2
Initial Final Changes
1 3 180
1 5 265
3 3 147
3 7 155
当表1的“Initial”和“Final”列的行等于表2中的每一行时,我需要将表1的最后一列(Changes)与表2的最后一列(Changes)相加,生成一个表格如:
Initial Final Changes
1 1 200
1 3 680
1 5 265
3 1 250
3 3 322
3 7 155
我正在尝试这种方式,但出现错误:
for (row in 1:nrow(t1) {
t2[t2$Initial == row$Initial && t2$Final == row$Final,t2$Changes] <- row$Changes + t2[t2$Initial == row$Initial && t2$Final == row$Final,t2$Changes]
}
有人可以帮助我吗?
您可以连接两个表并在连接的表上创建一个新列来求和:
joined = merge(t1,t2,by = c("Initial","Final"),all=T)
joined["Changes.final"] <- apply(joined[,c("Changes.x","Changes.y")],
FUN = function(x)sum(x,na.rm=T), MARGIN = 1)
数据:
t1 = data.frame(
"Initial" = c(1,1,3,3),
"Final" = c(1,3,1,3),
"Changes" = c(200,500,250,175)
)
t2 = data.frame(
"Initial" = c(1,1,3,3),
"Final" = c(3,5,3,7),
"Changes" = c(180,265,147,155)
)
您可以使用
aggregate
和 rbind
。
aggregate(Changes ~ ., rbind(t1, t2), sum)
# Initial Final Changes
#1 1 1 200
#2 3 1 250
#3 1 3 680
#4 3 3 322
#5 1 5 265
#6 3 7 155