【发布时间】:2011-08-24 10:49:17
【问题描述】:
需要使用nlm函数估计两个参数;
fit<-nlm(hood2par,c(x01[i],x02[j]),iterlim=300, catch=x[,c(3,4,5)],sp=.5)
其中hood2par 是修改后的逻辑
nlm的收敛取决于这些参数的起始值。为了找到这样的初始值,我会自动生成两个初始值向量
x01 = seq(-10,-20,-0.1)
x02 = seq(0.1,0.9,0.01)
接下来我创建一个包含在double for()中的例程,以查找导致函数收敛的值:
for (i in 1:length(x01)) { for (j in 1:length(x02)) {
fit <- NULL
try(fit <- nlm(hood2par, c(x01[i],x02[j]), iterlim = 300, catch = x[,c(3,4,5)],
sp = .5),
silent = TRUE)
stopifnot(is.null(fit))}}
我遇到的问题是,当我在函数中包含上一个例程时:
FFF <- function(x01, x02, catch){
for (i in 1:length(x01)) {
for (j in 1:length(x02)) {
fit <- NULL
try(fit <- nlm(hood2par, c(x01[i], x02[j]), iterlim = 300,
catch = x[,c(3,4,5)], sp = .5),
silent = TRUE) # does not stop in the case of err
stopifnot(is.null(fit))
}
}
return(fit)
}
我无法从 FFF() 获得“适合”值:
> fit.fff<-FFF(x01,x02,catch)
#Error: is.null(fit) is not TRUE
>fit.fff
fit.fff
Error: object 'fit.fff' not found
我使用stopifnot(is.null(fit)) 在 fit 不为 NULL 时停止循环(因为 fit 在 try(...) 之前定义为 NULL 对象)。关于你分享的try代码,我只需要这个;
res <- try(some_expression)
if(inherits(res, "try-error"))
{
#some code to keep loops running
} else
{
#stop the loops and gather "res"
}
我尝试在条件语句的第二个参数中包含 break 函数,但它不能在我的 R 版本中运行...知道吗??
【问题讨论】:
-
如果您在代码中留出空间并缩进,它会使它so更容易阅读!
-
感谢加文的评论
-
@Juan:说“它不运行”不够具体,没有用处。它会抛出错误吗?如果是这样,哪个错误?还是它只是给出与预期不同的行为?请提供更多详细信息!
-
@Juan:此外,当代码可重现时,问题更容易解决,而您的代码则不行(因为没有提供
hood2par)。
标签: r error-handling for-loop nlm