[R] Parameter names in nls

rhelp.20.trevva at spamgourmet.com rhelp.20.trevva at spamgourmet.com
Mon Jul 21 17:49:45 CEST 2008

Dear R-help,

Could you please examine the following code, and see if I have discovered a bug or not, or am just doing something silly.

I am trying to create a package to do fish stock assessment using the nls() function to fit the modelled stock size to the various pieces of information that we have. The main problem with this sort of task is that the number and type of parameters that go into the model are highly variable between stocks, but the method needs to be "intelligent" enough to handle this. The way I have chosen to handle this is through the names in my parameter vector, and using code inside the objective function to figure out which parameter is which.

The problem I have encountered is that I don't think nls() always passes a named vector - indeed, after the first set of function evaluations, it drops the names from the parameters vector altogether. I believe this to be a bug - it certaintly plays havoc with my code!

As a demonstration of this problem, consider the piece of code below. It is basically fitting a straight line to some synthetic data (with noise). I have setup the objective function so that it prints the names of the parameters every time that it is called. As you can see, the names are there to begin with, but rapidly disappear after the first "step" is made.

Is this a bug? Or is it intended behaviour? Or is this a completely daft approach I am taking?

I look forward to your comments.



fitting.fn <-function(x,params) {
  #The model - so that it works
  y <- params[1] + x*params[2]
  #How I would prefer it to work
#  y <- params["a"] + x*params["b"]

  #Display information about function eval
  cat(paste("Evaluation # :",counter,"\t Names :"))
  counter <<- counter +1
counter <<- 1

data.x <- 1:50
data.y <- pi*data.x + rnorm(50,sd=20)
ips <-  c(a=0,b=0)

More information about the R-help mailing list