[R] Fwd: Re: Fitting exponential curve to data points

Stephen Tucker brown_emu at yahoo.com
Tue Jul 24 13:29:43 CEST 2007


Hope these help for alternatives to lm()? I show the use of a 2nd order
polynomial as an example to generalize a bit.

Sometimes from the subject line two separate responses can appear as reposts
when in fact they are not... (though there are identical reposts too). I
should probably figure a way around that.

--- Stephen Tucker <brown_emu at yahoo.com> wrote:

> ## Data input
> input <-
> "Year	Count
> 1999	3
> 2000	5
> 2001	9
> 2002	30
> 2003	62
> 2004	154
> 2005	245
> 2006	321"
> 
> dat <- read.table(textConnection(input),header=TRUE)
> dat[,] <- lapply(dat,function(x) x-x[1])
>           # shifting in origin; will need to add back in later
> 
> ## Nonlinear least squares
> plot(dat)
> out <- nls(Count~b0*exp(b1*Year),data=dat,
>            start=list(b0=1,b1=1))
> lines(dat[,1],fitted(out),col=2)
> out <- nls(Count~b0+b1*Year+b2*Year^2,data=dat, #polynomial
>            start=list(b0=0,b1=1,b2=1))
> lines(dat[,1],fitted(out),col=3)
> 
> ## Optim
> f <- function(.pars,.dat,.fun) sum((.dat[,2]-.fun(.pars,.dat[,1]))^2)
> fitFun <- function(b,x) cbind(1,x,x^2)%*%b
> expFun <- function(b,x) b[1]*exp(b[2]*x)
> 
> plot(dat)
> out <- optim(c(0,1,1),f,.dat=dat,.fun=fitFun)
> lines(dat[,1],fitFun(out$par,dat[,1]),col=2)
> out <- optim(c(1,1),f,.dat=dat,.fun=expFun)
> lines(dat[,1],expFun(out$par,dat[,1]),col=3)



       
____________________________________________________________________________________
Got a little couch potato? 
Check out fun summer activities for kids.



More information about the R-help mailing list