Stephen Tucker
2007-Jul-24 11:29 UTC
[R] Fwd: Re: Fitting exponential curve to data points
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.
On 7/24/07, Stephen Tucker <brown_emu at yahoo.com> wrote:> Hope these help for alternatives to lm()? I show the use of a 2nd order > polynomial as an example to generalize a bit.Great, thanks. If I want to demonstrate that a non-linear curve fits better than an exponential, what's the best measure for that? Given that neither of nls() or optim() provide R-squared. Sorry if these are really silly questions.> 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.Nope, my fault, I didn't read them properly and thought you were demonstrating a different way to do exponential curves. Cheers, Andrew.