首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用nls跳过数据表计算中的错误

使用nls跳过数据表计算中的错误
EN

Stack Overflow用户
提问于 2018-09-26 22:56:43
回答 1查看 171关注 0票数 1

这个问题建立在我之前问过的一个问题上,Exponential curve fitting with nls using data.table groups

我使用nls将指数曲线拟合到多个组的数据表对象。并不是所有的数据都符合指数模型,nls有时会抛出错误,停止对其余组的所有进一步计算。

我尝试使用tryCatch跳过有问题的组,但我在下面附加了一个MWE,但我得到了所有新列的错误输出。如何跳过为有问题的组计算nls值?

代码语言:javascript
运行
复制
## Example data table
DT <- data.table(
     x = c(1,2,3,4,5,6,7,8,
           1,2,3,4,5,6,7,8,
           1,2,3,4,5,6,7,8),
     y = c(15.4,16,16.4,17.7,20,23,27,35,
           25.4,26,26.4,27.7,30,33,37,45,
           27.4,28,28.4,29.7,32,35,39,47),
groups = c(1,1,1,1,1,1,1,1,
           2,2,2,2,2,2,2,2,
           3,3,3,3,3,3,3,3)
)

## Fit exponential curve using starting values a,b,c for each group 
DT[, c("sigma", "a", "b", "c") := {
    c.0 <- min(y) * 0.5
    model.0 <- lm(log(y - c.0) ~ x, data=.SD)
    start <- list(a=exp(coef(model.0)[1]), b=coef(model.0)[2], c=c.0)
    model <- nls(y ~ a * exp(b * x) + c,
        data=.SD, 
        start=start, 
        control=nls.control(maxiter=500))
    c(.(sigma=summary(model)$sigma), as.list(coef(model)))
},
by=.(groups)]

## Modify data table to ruin nls model for group 2
set(DT, i=16L, j="y", value=3)

## Calculation works for group 1 but stops for group 2 and onwards
DT[, c("sigma", "a", "b", "c") := {
    c.0 <- min(y) * 0.5
    model.0 <- lm(log(y - c.0) ~ x, data=.SD)
    start <- list(a=exp(coef(model.0)[1]), b=coef(model.0)[2], c=c.0)
    model <- nls(y ~ a * exp(b * x) + c,
        data=.SD, 
        start=start, 
        control=nls.control(maxiter=500))
    c(.(sigma=summary(model)$sigma), as.list(coef(model)))
},
by=.(groups)]

## My poor attempt at using a tryCatch just gives NA to every column
DT[, c("sigma","a", "b", "c") := {
    c.0 <- min(y) * 0.5
    model.0 <- lm(log(y - c.0) ~ x, data=.SD)
    start <- list(a=exp(coef(model.0)[1]), b=coef(model.0)[2], c=c.0)
    model <- tryCatch(
        {
            nls(y ~ a * exp(b * x) + c,
                data=.SD, 
                start=start, 
                control=nls.control(maxiter=500))
            c(.(sigma=summary(model)$sigma), as.list(coef(model)))
        },
        error=function(err){
            return(NA_real_)
        }
    )
},
by=.(groups)]
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52520710

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档