【发布时间】:2015-11-11 01:20:54
【问题描述】:
我有一个如下所示的数据框 X:
A B C D E Identifier
1 2 3 4 5 a
2 3 2 2 1 b
4 5 4 5 3 a
2 3 4 5 6 a
0 0 1 2 3 a
1 2 1 1 1 b
(这里的范围是 6,因为记录观察的时间段是 6。)
现在我想根据标识符计算 A、B、C、D、E 中的每一个的平均值。为此,我使用了 Process1
avgcalls <- function(calls){
totcalls <- sum(calls)
out <- totcalls/6
return(out)
}
avgcallsdf <- data.frame((aggregate(X[, 1:4], by = X[6], avgcalls)))
输出是这样的
Identifier A B C D
1 a 1.66667 1.6666667 2.0 2.5
2 b 0.50000 0.8333333 0.5 0.5
或者我做了(请提出更好的方法)
Process2
samp1<-D[which(D$Identifier=='a')] #creating one dataframe with identifier as 'a'
samp2<-D[which(D$Identifier=='b')]#creating another dataframe with'b'as identifier
#calculating means
mean1<-sum(sampl$A, na.rm=TRUE)/6
mean2<-sum(sampl$B, na.rm=TRUE)/6
mean3<-sum(sampl$C, na.rm=TRUE)/6
mean4<-sum(sampl$D, na.rm=TRUE)/6
mean5<-sum(samp1$E, na.rm=TRUE)/6
finaldf<-data.frame(mean1,mean2,mean3,mean4,mean5)
与上面的 samp2 类似 两个结果是相同的。
我的实际数据有 1008 列和大约 80,000 行,结果是否会有所不同 如果存在 NA,则处理 1 和 Process2?
我看过这个Getting different results using aggregate() and sum() functions in R,但它不是很有帮助
【问题讨论】: