需要使用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”值:
> fit.fff<-FFF(x01,x02,catch)
#Error: is.null(fit) is not TRUE
>fit.fff
fit.fff
Error: object 'fit.fff' not found当fit不是NULL时,我使用stopifnot(is.null(fit))停止循环(因为fit在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 version...Any思想?
发布于 2011-08-24 11:07:51
调用FFF时,如果nlm成功完成,则在try块内分配fit,并激活stopifnot条件,引发错误。
胡思乱想,你是说
stopifnot(!is.null(fit))对于将来的参考,与try一起使用的标准代码块是
res <- try(some_expression)
if(inherits(res, "try-error"))
{
#some error handling code
} else
{
#normal execution
}https://stackoverflow.com/questions/7174226
复制相似问题