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 

按照这个答案,我能够在没有参数的情况下解决这个问题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复制模型 1模型 2的参数poly

到目前为止我失败的尝试

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

如何apoly方法中包含参数?


数据

set.seed(42)
dat <- data.frame(y=sort(rexp(100, 1) + rnorm(100)), x=1:100)
4

1 回答 1

1

令 coef 为包括 a 和 cbind 1 到 poly 的整个系数向量:

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

或者只是添加a到poly:

nls(y ~ exp(a + poly(x, 2, raw = TRUE) %*% coef), data = dat,
  start = list(a = 0, coef = numeric(2)))
于 2020-04-05T13:01:17.333 回答