2011-08-24 27 views
1

需要使用nlm函數估計兩個參數;選擇nlm起始值問題

fit<-nlm(hood2par,c(x01[i],x02[j]),iterlim=300, catch=x[,c(3,4,5)],sp=.5) 

其中hood2par是NLM的改進的Logistic

收斂依賴於這些參數的初始值。找到這樣的初始值I自動生成初始值

的兩個向量
x01 = seq(-10,-20,-0.1) 
x02 = seq(0.1,0.9,0.01) 

下一I創建包括在一個雙例程()來發現導致函數的收斂值:

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))停止循環時,配合不是NULL(如配合試之前定義爲NULL對象(...))。關於你分享的嘗試代碼,我只需要這個;

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

我想包括在condictional的第二個參數的break功能,但它doesn't在我的[R版本上運行...任何想法?

+0

它使*所以*更容易閱讀如果你空出來並縮進你的代碼! –

+0

非常感謝Gavin對你的評論 –

+0

@Juan:說「不運行」並不足夠有用。它會拋出一個錯誤嗎?如果是這樣,哪個錯誤?還是它只是給予不同於預期的行爲?更多細節請! –

回答

4

當你調用FFF,try塊內,如果nlm成功完成,那麼fit分配,並stopifnot條件被激活時,拋出一個錯誤。

狂亂的猜測,您的意思是否

stopifnot(!is.null(fit)) 

以供將來參考,用於與try使用代碼的標準塊被

res <- try(some_expression) 
if(inherits(res, "try-error")) 
{ 
    #some error handling code 
} else 
{ 
    #normal execution 
}