R 可变长度的差分误差

R 可变长度的差分误差,r,aggregate,R,Aggregate,我想总结一些数据: studentid friend Gfriend 214 30401006 0 0 236 30401006 0 0 208 30401006 1 0 229 30401006 0 0 207 30401006 0 0 278 30401007 1 0 250 30401007 1 0 266 304

我想总结一些数据:

    studentid friend Gfriend
214  30401006      0       0
236  30401006      0       0
208  30401006      1       0
229  30401006      0       0
207  30401006      0       0
278  30401007      1       0
250  30401007      1       0
266  30401007      1       0
254  30401007      1       1
277  30401007      1       1
243  30401007      1       1
结果应该如下所示:

studentid friend Gfriend
30401006   1      0
30401007   6      3
当我尝试时:
agg=aggregate(c(friend)~studentid,data=df,FUN=sum)
我得到了所需的结果(但只针对friend变量)。 但当我尝试:
agg=aggregate(c(friend,Gfriend)~studentid,data=df,FUN=sum)
我得到:

model.frame.default(formula=c(friend,Gfriend)~studentid中存在错误, :可变长度不同(针对“studentid”找到)

我检查了变量的长度(length(var)),它们都是相同的,而且没有NA,所以我不知道这个错误是从哪里来的

为什么会发生这种情况?

您也可以尝试“通过”

studentidfriendEDIT:添加了
na.rm=T
,以解决有关排除NAs的评论

查看“plyr”套餐

library(plyr)

#split by "studentid" and sum all numeric colums 

ddply(df, .(studentid), numcolwise(sum, na.rm=T))

studentid friend Gfriend
1  30401006      1       0
2  30401007      6       3

你很接近,试着用
cbind
而不是
c
来代替
aggregate(cbind(friend,Gfriend)~studentid,df,sum)
效果很好。非常感谢David!或者,如果你的数据中没有其他列,你可以这样做:
aggregate(.~studentid,df,sum)
如何使用David的代码而不丢弃NA。我给出的示例中没有NA,但我总结的完整数据中有NA,前面的代码省略了它们。我尝试了NA.pass,但在有NA的coulmns中得到了NA。当
&
为.NA时,使用
case_替换NAs。
library(plyr)

#split by "studentid" and sum all numeric colums 

ddply(df, .(studentid), numcolwise(sum, na.rm=T))

studentid friend Gfriend
1  30401006      1       0
2  30401007      6       3