代码之家  ›  专栏  ›  技术社区  ›  nico

r:捕获'nls中的错误`

  •  6
  • nico  · 技术社区  · 15 年前

    我在拟合一些指数数据 nls .

    我使用的代码是:

    fit <- nls(y ~ expFit(times, A, tau, C), start = c(A=100, tau=-3, C=0))
    

    expFit 定义为

    expFit <- function(t, A, tau, C)
        {
        expFit <- A*(exp(-t/tau))+C
        }
    

    这对我的大多数数据都很有效,对于这些数据,提供的起始参数(100、-3和0)都很有效。但有时,我的数据与这些参数不符,我会从 NLS (例如,“奇异梯度”或类似的东西)。如何“捕捉”这些错误?

    我试着做一些像

    fit <- NULL
    fit <- nls(...)
    
    if (is.null(fit))
        {
        // Try nls with other starting parameters
        }
    

    但这不起作用,因为 NLS 似乎停止了执行和之后的代码 NLS 不会执行…

    有什么想法吗?

    谢谢 尼科

    1 回复  |  直到 12 年前
        1
  •  10
  •   walkytalky    12 年前

    我通常使用这个技巧:

    params<-... # setup default params.
    
    while(TRUE){
    
    fit<-NULL
    try(fit<-nls(...)); # does not stop in the case of error
    
    if(!is.null(fit))break; # if nls works, then quit from the loop
    
    params<-... # change the params for nls
    
    }
    
    推荐文章