1

需要使用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 对象)。关于您共享的尝试代码,我只需要这个;

res <- try(some_expression)
if(inherits(res, "try-error"))
{
  #some code to keep loops running
} else
{
  #stop the loops and gather "res" 
}

我试图break在条件语句的第二个参数中包含该函数,但它没有在我的 R 版本中运行……知道吗?

4

1 回答 1

4

当您调用时,如果成功完成,则FFF在 try 块内分配,并激活条件,引发错误。nlmfitstopifnot

胡乱猜测,你的意思是

stopifnot(!is.null(fit))

为了将来参考,用于使用的标准代码块try

res <- try(some_expression)
if(inherits(res, "try-error"))
{
  #some error handling code
} else
{
  #normal execution
}
于 2011-08-24T11:07:51.017 回答