R:捕获“nls”中的错误 [英] R : catching errors in `nls`

查看:266
本文介绍了R:捕获“nls”中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 nls 来拟合一些指数数据。



我使用的代码是: / p>

  fit<  -  nls(y〜expFit(times,A,tau,C),start = c(A = 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))
{
/ /尝试nls与其他启动参数
}

但这不会工作,因为 nls 似乎停止执行,代码在 nls 将不会执行...



任何想法?



感谢
nico

解决方案

我通常使用这个技巧:

  params< -...#设置默认参数。 

while(TRUE){

fit< -NULL
try(fit< -nls(...)); #不停止在错误的情况下

if(!is.null(fit))break; #如果nls工作,然后从循环中退出

params< -...#更改nls


$ b


I'm fitting some exponential data using nls.

The code I'm using is:

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

expFit is defined as

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

This works well for most of my data, for which the starting parameters provided (100, -3 and 0) work well. Sometimes, though, I have data that doesn't go well with those parameters and I get errors from nls (e.g. "singular gradient" or things like that). How do I "catch" these errors?

I tried to do something like

fit <- NULL
fit <- nls(...)

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

But this won't work because nls seems to stop the execution and the code after nls will not execute...

Any ideas?

Thanks nico

解决方案

I usually use this trick:

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

}

这篇关于R:捕获“nls”中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆