如何在nls中的poly方法中包含参数“ a”?

问题描述 投票:1回答:1

我想在指数poly函数中使用nls。考虑以下两种模型。

## model 1
nls(y ~ exp(a + b*x), data=dat, start=list(a=0, b=0))
#           a           b  ## coefs
# -4.13220156  0.05972285 

## model 2
nls(y ~ exp(a + b*x + c*I(x^2)), data=dat, start=list(a=0, b=0, c=0))
#          a          b          c 
# -3.0603943  0.0300680  0.0001941 

跟随this answer,我能够在没有参数a的情况下解决此问题。

nls(y ~ exp(b*x), data=dat, start=list(b=0))
#       b 
# 0.01071 
nls(y ~ exp(poly(x, 1, raw=T) %*% coef), data=dat, start=list(coef=0))
#    coef 
# 0.01071 

nls(y ~ exp(b*x + c*I(x^2)), data=dat, start=list(b=0, c=0))
#          b          c 
# -0.0562947  0.0007633 
nls(y ~ exp(poly(x, 2, raw=T) %*% coef), data=dat, start=list(coef=rep(0, 2)))
#      coef1      coef2 
# -0.0562947  0.0007633

但是,我找不到一种方法来包含参数a以从上方用poly重现模型1模型2

到目前为止,我的尝试失败

nls(y ~ exp(c(a, poly(x, 2, raw=T)) %*% coef), data=dat, 
    start=list(coef=setNames(rep(0, 3), letters[1:3])))
nls(y ~ exp(cbind(a, poly(x, 2, raw=T)) %*% coef), data=dat, 
    start=setNames(replicate(3, list(0)), letters[1:3]))
nls(y ~ exp(cbind(as.matrix(a), poly(x, 2, raw=T)) %*% coef), data=dat, 
    start=list(coef=setNames(replicate(3, list(0)), letters[1:3])))
nls(y ~ a*exp(poly(x, 2, raw=T) %*% coef), data=dat, 
    start=list(coef=setNames(replicate(3, list(0)), letters[1:3])))
nls(y ~ exp(a*lapply(coef, `[`, 1) + poly(x, 2, raw=T) %*% lapply(coef, `[`, -1)), 
    data=dat, start=list(coef=setNames(rep(0, 3), letters[1:3])))
nls(y ~ a*lapply(coef, `[`, 1)*exp(poly(x, 2, raw=T) %*% lapply(coef, `[`, -1)), 
    data=dat, start=list(coef=setNames(rep(0, 3), letters[1:3])))

产生相似的错误消息:

Error in nls(y ~ exp(c(a, poly(x, 2, raw = T)) %*% coef), data = dat,  : 
  parameters without starting value in 'data': a

如何在a方法中包含参数poly


数据

set.seed(42)
dat <- data.frame(y=sort(rexp(100, 1) + rnorm(100)), x=1:100)
r nls poly
1个回答
1
投票
让coef为包括a和将1绑定到poly的整个系数向量:

nls(y ~ exp(cbind(1, poly(x, 2, raw = TRUE)) %*% coef), data = dat, start = list(coef = numeric(3)))

或仅将a添加到多边形:

nls(y ~ exp(a + poly(x, 2, raw = TRUE) %*% coef), data = dat, start = list(a = 0, coef = numeric(2)))

© www.soinside.com 2019 - 2024. All rights reserved.