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

Tianchan Niu Niu at isis.georgetown.edu
Wed Jan 2 20:41:35 CET 2013

Thank you Gabor for your quick response, but it didn't solve the issue, I still got the same error message when calling the function.
BTW, is there any other way to get the prediction interval of nonlinear regression than using nls2 package? If yes, I might be able to avoid the possible hidden problems.


-----Original Message-----
From: Gabor Grothendieck [mailto:ggrothendieck at gmail.com] 
Sent: Wednesday, January 02, 2013 2:16 PM
To: Tianchan Niu
Cc: r-help at r-project.org
Subject: Re: [R] Need help with self-defined function to perform nonlinear regression and get prediction interval

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:
or source it from the svn repo:

More information about the R-help mailing list