如何高效实现 dplyr do call for lmer 函数?

How to efficiently implement dplyr do call for lmer function?

我有一个包含 ~400000 行的数据集,我正在尝试使用 R 中的 dplyr do 调用来提取 lme4 混合模型方差分量。函数是:

myfunc <- function(dat) {
    if (sum(!is.na(dat$value)) > 840) {  # >70% data present 
           v = data.frame(VarCorr(lmer(value ~ 0 + (1|gid) + (1|trial:rep) + (1|trial:rep:block), data=dat)))
           data.frame(a=round(v[1,4]/(v[1,4]+(v[4,4]/2)),2), b=round(v[1,4],2), c=round(v[4,4],2), n_obs=nrow(dat), na_obs=sum(is.na(dat$value))) 
    } else { 
        data.frame(a=NA, b=NA, c=NA, n_obs= nrow(dat), na_obs=sum(is.na(dat$value)))
    }
}

通过四个分组变量对数据进行分组后,通过 dplyr do 调用调用此函数。最后的 dplyr 调用是:

system.time(out <- tst %>% group_by(iyear,ilocation,trait_id,date) %>% 
          do(myfunc(.)))

现在,当此代码在 11000 行的较小测试数据帧上 运行 时,大约需要 25 秒。但是 运行 在一整套 443K 行上使用它大约需要 8-9 个小时才能完成,这非常慢。很明显,有一部分代码降低了性能,但我似乎无法弄清楚是 lmer 部分还是 dplyr 导致了速度下降。我感觉函数处理矢量化操作的方式有问题但不确定。我尝试在函数调用之外初始化 'out' 矩阵,但它并没有提高性能。
不幸的是,我没有可共享的较小的可重现数据集。但想听听您对如何使此代码更高效的想法。

解决方法: 来自 parallel 包的 mclapply 函数来拯救。正如@gregor 正确指出的那样,它可能是 lmer 部分正在减慢速度。最后我结束了函数调用的并行化:

myfunc <- function(i) {
     dat = tst[tst$comb==unique(tst$comb)[i],]  #comb is concatenated iyear,ilocation....columns
     if (sum(!is.na(dat$value)) > 840) {  # >70% data present per column
         v = data.frame(VarCorr(lmer(value ~ 0 + rand_factor + nested_random_factor), data=dat)))
         data.frame(trait=unique(tst$comb)[i], a=round(v[1,4])/5, b=round(v[1,4],2), c=round(v[4,4],2), n_obs=nrow(dat), na_obs=sum(is.na(dat$value))) 
     } else {
          data.frame(trait=unique(tst$comb)[i], a=NA, b=NA, c=NA, n_obs= nrow(dat), na_obs=sum(is.na(dat$value))) 
     }
}

#initialize an empty matrix
out <- matrix(NA,length(unique(tst$comb)),6)

## apply function in parallel. output is list
n_cores = detectCores() - 2
system.time(my.h2 <- mclapply(1:length(unique(tst$comb)),FUN = myfunc, mc.cores = n_cores))

一台 12 核 unix 机器大约需要 2 分钟才能完成。