【发布时间】:2017-10-17 12:41:43
【问题描述】:
我正在尝试通过用 lapply 替换 for 循环来加速我的代码。我在许多不同的样本上运行 nls 模型并提取系数,但某些模型对于某些样本没有收敛。我可以使用带有 trycatch 的 for 循环来处理这个问题,以忽略这些样本,但我无法让它与 lapply 一起使用。当我运行它时,我得到了我的 sample.code 和 NULL 的列表,我应该在哪里放置 return(nls.dat)?部分,所以我不只是结束 NULL?
test.func <- function (SCDF){
tryCatch({
mod.allDIDO <- nlsLM (BM~Cr*(1 - R * exp(-Kr*day) - (1 - R) * exp(-Kr2*day)), data=dat[dat$sample.code %in% SC,], start=list(Cr=DI.Cr,R=DI.r,Kr=DI.Kr,Kr2=DI.Kr2),
control = nls.lm.control(maxiter = 500), lower = c(-Inf, 0, 0, 0), upper = c(Inf, 1, Inf, Inf))
nls.dat <- c("df", coef(mod.allDIDO)[1], coef(mod.allDIDO)[2], coef(mod.allDIDO)[3], coef(mod.allDIDO)[4], deviance(mod.allDIDO), logLik(mod.allDIDO))
return (nls.dat)
}, error = function(e){})
}
test1 <- lapply(split(dat, dat$sample.code), test.func)
已编辑以包含一些数据并回复 Carl: 我尝试了你的建议(Carl),但我仍然得到 NULL,请参阅缩减版
x1 <- 0:60
y1 <- 774*(1 - 0.5 * exp(-0.2*x1) - (1 - 0.5) * exp(-0.016*x1))
test.dat <- data.frame (x1, y1)
nls.dat <- tryCatch({
mod.allDIDO <- nlsLM(y1~Cr*(1 - R * exp(-Kr*x1) - (1 - R) * exp(-Kr2*x1)),
data=test.dat,
start=list(Cr=774,R=0.5,Kr=0.2,Kr2=0.016),
control = nls.lm.control(maxiter = 500),
lower = c(-Inf, 0, 0, 0),
upper = c(Inf, 1, Inf, Inf))
nls.dat <- c("df", coef(mod.allDIDO)[1],
coef(mod.allDIDO)[2],
coef(mod.allDIDO)[3],
coef(mod.allDIDO)[4],
deviance(mod.allDIDO),
logLik(mod.allDIDO))
return(nls.dat)
}, error = function(e){})
nls.dat ## NULL
【问题讨论】: