我正在使用生存分析技术进行中介分析。这需要使用 for 循环进行引导。我的挑战是这个模型需要很长时间才能运行,如果可能的话我想对其进行优化。我听说将其转换为 lapply 会有所帮助,或者并行化此代码也可能会有所帮助。
这是我下面的代码。您可以忽略系统时间。
system.time(
for(i in 1:ntrials-1) {
ntrials <- 10000
npat <-4413
sampledata<-mgfipdma1[sample(nrow(mgfipdma1),npat, replace=TRUE),]
direct <- fixef(coxme(Surv(deathcont/365.25,dth)~ sex + gf + agec10 + ht + smk + diab + offpump + gsum + agsum + statin + LAD + seq + (1|trial), data= mgfipdma1))
total <- coxs <- fixef(coxme(Surv(deathcont/365.25,dth)~ sex + agec10 + ht + smk + diab + offpump + gsum + agsum + statin + LAD + seq + (1|trial), data= mgfipdma1))
indirect2 <-exp(total-direct)
indirect<-rbind(indirect, indirect2)
}
)
quantile(indirect, c(0.025, 0.50, 0.975))
感谢您提供的任何帮助或建议。
到目前为止,我已经尝试过各种中介包,如 mediate、lavaan,但没有一个能够使用具有协变量的混合效应 cox 比例风险模型,就像我正在使用的那样(据我所知)。因此,我正在使用这个 for 循环,但运行需要大量时间(10k 次迭代需要数周)。我只是想知道是否有任何方法可以优化我的代码以加快此过程,而无需使用云。
要并行化任务,您可以使用 parallel 包中的 mclapply。
您的代码可能如下所示:
library(parallel)
ncores <- detectCores()
indirect <- mclapply(1:ntrials-1,
function(i){
ntrials <- 10000
npat <-4413
sampledata<-mgfipdma1[sample(nrow(mgfipdma1),npat, replace=TRUE),]
direct <- fixef(coxme(Surv(deathcont/365.25,dth)~ sex + gf + agec10 + ht + smk + diab + offpump + gsum + agsum + statin + LAD + seq + (1|trial), data= mgfipdma1))
total <- coxs <- fixef(coxme(Surv(deathcont/365.25,dth)~ sex + agec10 + ht + smk + diab + offpump + gsum + agsum + statin + LAD + seq + (1|trial), data= mgfipdma1))
indirect2 <-exp(total-direct)
return(indirect2)
}, mc.cores = ncores)
indirect <- do.call(rbind, indirect)