我正在使用 lmer 进行混合建模,并想探索随机化数据的效果。下面的代码在速度方面可以改进吗?就目前而言,我目前的规格需要几天时间来运行我的实际数据......从我能够找到的情况来看,sapply 是要走的路。我希望我错了。
library(lme4)
##Generate real data
real.data=data.frame(cat1=factor(rep(c("A","B","C","D"),500)),cat2=factor(rep(c("E","F","G","H"),500)), matrix(runif(12000),ncol=6))
##Apply lmer model for each data columm and extract variance estimates with VarCorr for 1000 randomizations of the real.data frame.
random=sapply(1:1000,function(z){print(z)
##Generate a randomized data set by sampling first two factor columns
sample=data.frame(cat1=factor(sample(real.data$cat1)),cat2=factor(sample(real.data$cat2)), real.data[,3:8])
sapply(3:dim(sample)[2],function(y){print(y)
##Apply REML to each column of data, with 'cat1' and 'cat2' as random effects, including cat1:cat2 interaction
model=lmer(sample[,y]~(1|cat1)+(1|cat2)+(1|cat1:cat2), data=sample)
##Extract the estimates of the random effect terms
c(as.numeric(VarCorr(model)$cat1),as.numeric(VarCorr(model)$cat2),as.numeric(VarCorr(model)$'cat1:cat2'))
})
})