Search code examples
rnls

How to pass a long list of parameters to `nls` function in R


The nls function works normally like the following:

 x <- 1:10
 y <- 2*x + 3                            # perfect fit
 yeps <- y + rnorm(length(y), sd = 0.01) # added noise
 nls(yeps ~ a + b*x, start = list(a = 0.12345, b = 0.54321))#

Because the model I use have a lot of parameters or I don't know beforehand what will be included in the parameter list, I want something like following

tmp <- function(x,p) { p["a"]+p["b"]*x }
p0 <- c(a = 0.12345, b = 0.54321)
nls(yeps ~ tmp(x,p), start = list(p=p0))

Does anyone know how to modify the nls function so that it can accept a parameter vector argument in the formula instead of many seperate parameters?


Solution

  • You can give a vector of init coefficients like this :

    tmp  <- function(x, coef){
           a <- coef[1]
           b <- coef[2]
           a +b*x
         }
    
    x <- 1:10
    yeps <- y + rnorm(length(y), sd = 0.01)  # added noise
    nls(yeps ~ a + b*x, start = list(a = 0.12345, b = 0.54321))#                     
    nls(yeps ~ tmp(x,coef), start = list(coef = c(0.12345, 0.54321)))
    
    Nonlinear regression model
      model:  yeps ~ tmp(x, coef) 
       data:  parent.frame() 
    coef1 coef2 
        3     2 
     residual sum-of-squares: 0.0016
    
    Number of iterations to convergence: 2 
    Achieved convergence tolerance: 3.47e-08 
    

    PS:

     example(nls)
    

    Should be a good start to understand how to play with nls.