[R] nls and if statements

John C Nash nashjc at uottawa.ca
Fri May 18 22:43:30 CEST 2012


Your issue is that nls returns "singular gradient", but I believe the real trouble is that
if or ifelse are not in the derivatives table. My own (experimental, but in R-forge)
package nlmrt has nlxb to mirror nls but be much more aggressive in finding a solution,
and it gives an error msg that ifelse is not in the derivatives table. It may be that nls
has an alternative for getting numerical derivatives (perhaps Doug Bates or Saikat DebRoy
could comment).

It may be better to convert to a function and use Nelder-Mead in optim, or better, nmk
from dfoptim which is more up to date. I'm uniquely positioned to say this, as I wrote the
version of Nelder-Mead in optim and I think it's getting long in the tooth, though it
still works remarkably well. One of the routines in minqa may be better for speed, but
possibly less stable.

Code:


wfn<-function(par, Cfl, Tsoil, Pw){
   K<-par[1]
   a<-par[2]
   b<-par[3]
   c<-par[4]
   z<-par[5]
   m<-length(Pw)
   res<-rep(NA,m)
   for (i in 1:m){
     tmp<-1
     if (Pw[i] <= z) tmp<-exp(-a*Tsoil[i])
     ff<-K*tmp*exp(-b*Pw[i])+c
     res[i]<-Cfl[i]-ff
   }
   as.numeric(crossprod(res))
}
a1<-optim(st,wfn, control=list(trace=1), Cfl=Cfl, Tsoil=Tsoil, Pw=Pw)

(which converges pretty fast)



Best, JN



More information about the R-help mailing list