rnlspoly

How to include parameter "a" in a poly approach in nls?


I want to use poly in a an exponential nls function. Consider following two models.

## 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 

Following this answer, I was able to solve this without parameter 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

However, I couldn't find a way to include parameter a to reproduce model 1 and model 2 from above with poly.

My failed attempts so far

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])))

yield similar error messages:

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

How may I include parameter a in a poly approach?


Data

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

Solution

  • Let coef be the entire coefficient vector including a and cbind 1 to poly:

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

    or just add a to poly:

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