我有一个如下所示的数据框 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
或者我做了(请提出更好的方法)
进程2
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 行,结果会有所不同吗 Process 1和Process2是否存在NA?
我看了这个Getting different results using aggregate() and sum() functions in R但这不是很有帮助
最佳答案
我们也可以使用data.table
library(data.table)
setDT(df1)[, lapply(.SD, mean), Identifier]
# Identifier A B C D E
#1: a 1.75 2.5 3.0 4.0 4.25
#2: b 1.50 2.5 1.5 1.5 1.00
如果我们需要 sum
除以 n=6
setDT(df1)[, lapply(.SD, function(x) sum(x, na.rm=TRUE)/6), Identifier]
# Identifier A B C D E
#1: a 1.166667 1.6666667 2.0 2.666667 2.8333333
#2: b 0.500000 0.8333333 0.5 0.500000 0.3333333
关于r - 在 R 与 sum(Dataframe$columns)/N 中使用聚合函数有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33642728/