对于每个级别的因子,我需要提取在data.frame的所有子集上聚合的值,除了当前的一个。例如,有几个受试者在几天内做了反应时间任务,我需要计算所有受试者和所有日子的平均反应时间,但不包括计算平均值的受试者。目前,我这样做:
library(lme4)
ddply(sleepstudy, .(Subject, Days), summarise,
avg_rt = mean(sleepstudy[sleepstudy$Subject != Subject &
sleepstudy$Days == Days,"Reaction"]), .progress="text")
它适用于小型数据集,但对于大型数据集,它可能非常慢。有没有办法更快地完成它?
答案 0 :(得分:3)
#create big dataset
n <- 1e4
set.seed(1)
sleepstudy <- data.frame(Reaction=rnorm(n),Subject=1:4,Days=sort(rep((1:(n/4)),4)))
library(plyr)
system.time(
res <- ddply(sleepstudy, .(Subject, Days), summarise,
avg_rt = mean(sleepstudy[sleepstudy$Subject != Subject &
sleepstudy$Days == Days,"Reaction"]))
)
#User System elapsed
#6.532 0.013 6.556
#use data.table for big datasets
library(data.table)
dt<- as.data.table(sleepstudy)
system.time(
{dt[,avg_rt:=mean(Reaction),by=Days];
dt[,n:=.N,by=Days];
dt[,avg_rt:=(avg_rt*n-Reaction)/(n-1)]}
)
#User System elapsed
#0.005 0.001 0.005
#test if results are equal
dt2 <- as.data.table(res)
setkey(dt2,Subject,Days)
setkey(dt,Subject,Days)
all.equal(dt[,avg_rt],dt2[,avg_rt])
#[1] TRUE
对于非常大的数据集,速度增益应该更加明显。我无法与较大的数据集进行比较,因为ddply
非常慢。
答案 1 :(得分:0)
使用lapply
和aggregate
可能会更快:
do.call("rbind", (lapply(unique(sleepstudy$Subject),
function(x)
cbind(Subject = x,
aggregate(Reaction ~ Days,
subset(sleepstudy, Subject != x),
mean)))))
<强>更新强>
我将这两个命令与system.time
进行了比较,看起来原来的速度较慢。
library(lme4)
library(plyr)
system.time(
ddply(sleepstudy, .(Subject, Days), summarise,
avg_rt = mean(sleepstudy[sleepstudy$Subject != Subject &
sleepstudy$Days == Days,"Reaction"]))
)
# user system elapsed
# 0.17 0.00 0.22
system.time(
do.call("rbind", (lapply(unique(sleepstudy$Subject),
function(x)
cbind(Subject = x,
aggregate(Reaction ~ Days,
subset(sleepstudy, Subject != x),
mean)))))
)
# user system elapsed
# 0.12 0.00 0.12