在R中按多列汇总数据框,但不更改行数[重复]

lnvxswe2  于 2023-10-13  发布在  其他
关注(0)|答案(1)|浏览(92)

这个问题已经有答案了

Add a new column of the sum by group [duplicate](1个答案)
15天前关闭。
在下面的例子中,我得到了这个数据:

x = c("a", "a", "a", "a", "b", "b")
y = c("s", "s", "t", "t", "s", "s")
z = c(1, 2, 3, 4, 5, 6)
data = data.frame(cbind(x, y, z))

然后,我需要将zxy相加,然后将总和作为w,如下所示。请注意,我不想合并行,结果应该仍然具有相同的行数。请问如何才能做到这一点?谢谢

x y z w
a s 1 3
a s 2 3
a t 3 7
a t 4 7
b s 5 5
b t 6 6
wbgh16ku

wbgh16ku1#

x = c("a", "a", "a", "a", "b", "b")
y = c("s", "s", "t", "t", "s", "t") # correction for last element
z = c(1, 2, 3, 4, 5, 6)
data = data.frame(x, y, z)

> ave(data$z,data[,c("x","y")],FUN=sum)
[1] 3 3 7 7 5 6

相关问题