[R] Need help with self-defined function to perform nonlinear regression and get prediction interval

Gabor Grothendieck ggrothendieck at gmail.com
Wed Jan 2 20:15:37 CET 2013


On Wed, Jan 2, 2013 at 1:23 PM, tn85 <niu at isis.georgetown.edu> wrote:
> Dear All,
>
> I was trying to call a self-defined function that performs nonlinear
> regression and gets the corresponding prediction upper limit using nls2
> package. However, weird thing happened. When I called the function in the
> main program, an error message "fitted(nlsmodel): object 'nlsmodel' not
> found" came up. But when I directly ran the codes inside the function, no
> error came up and the codes worked well. I have never encountered this
> problem with all the other self-defined functions, only this one, so I doubt
> it is caused by something in the nls2 package.
>
> I attached my main program and the function as follows. Thank you all in
> advance.
>
> # Main program
> rm(list=ls())
> x <- c(0,1,3,4,5,2,10,4,6,8,7)
> y <- seq(0,10,1)
> ftestnls(x,y) # Call the function
>
> # function 'ftestnls(v1,v2)'
> # v1 <- x
> # v2 <- y
> ftestnls <- function(v1,v2){
>   datalist <- list(v1=v1,v2=v2)
>   startvalues <- list(a0=v1[1],a1=0,a2=0)
>
>   # Perform nonlinear regression
>   require(nls2)
>   nlsmodel <- nls(v1~a0 + a1*v2 + a2
> *sin(2*pi*v2/365.25),data=datalist,start=startvalues, trace=TRUE)
>
>   # Fitted data and prediction interval
>   fitted <-
> predict(as.lm(nlsmodel),se.fit=TRUE,interval="confidence",level=0.95)
>   uplim <- fitted$fit[,3]
>
>   return(uplim)
> }
>

I was concerned that as.lm does not generalize well and removed it
from nls2. You can either use an older version of nls2:
   http://cran.r-project.org/src/contrib/Archive/nls2/
or source it from the svn repo:
  library(nls2)
  source("http://nls2.googlecode.com/svn-history/r8/trunk/R/as.lm.R")




More information about the R-help mailing list