# What's the most pain-free way to fit logistic growth curves in R?

This isn't as easy to Google as some other things as, to be clear, I'm not talking about logistic regression in the sense of using regression to predict categorical variables.

I'm talking about fitting a logistic growth curve to given data points. To be specific, $x$ is a given year from 1958 to 2012 and $y$ is the estimated global CO2 ppm (parts per million of carbon dioxide) in November of year $x$.

Right now it's accelerating but it's got to level off at some point. So I want a logistic curve.

I haven't found a relatively straightforward way to do this yet.

-
A logistic curve isn't the only curve that 'levels off'. Indeed a multiple of any continuous cdf would satisfy that requirement. – Glen_b Aug 23 '13 at 2:52
Use the package grofit Makes use of spline and growth curves. – user29804 Sep 2 '13 at 10:19
Nick, thank you very much for positng your code, I was just wondering how to write it as an equation? in the code the values C, a and K refer to which parameters? – user31660 Oct 18 '13 at 13:26
I think you are taking me to be @user2581681. I just edited their answer. – Nick Cox Oct 18 '13 at 15:45

See the nls() function. It has a self starting logistic curve model function via SSlogis(). E.g. from the ?nls help page

> library("nls")
> DNase1 <- subset(DNase, Run == 1)
>
> ## using a selfStart model
> fm1DNase1 <- nls(density ~ SSlogis(log(conc), Asym, xmid, scal),
+                  DNase1)


I suggest you read the help pages for these functions and probably the linked references if possible to find out more.

-

I had the same question a little while ago. This is what I found:

Fox and Weisberg wrote a great supplemental article using the nls function (both with and without the self-starting option mentioned by Gavin). It can be found here:

http://socserv.mcmaster.ca/jfox/Books/Companion/appendix/Appendix-Nonlinear-Regression.pdf

From that article, I ended up writing a function for my class to use when fitting a logistic curve to their data:

###Log fit - be sure to use quotes around the variable names in the call
log.fit <- function(dep, ind, yourdata){
#Self-starting...

y <- yourdata[, dep]
x <- yourdata[, ind]

log.ss <- nls(y ~ SSlogis(x, phi1, phi2, phi3))

#C
C <- summary(log.ss)$coef[1] #a A <- exp((summary(log.ss)$coef[2]) * (1/summary(log.ss)$coef[3])) #k K <- (1 / summary(log.ss)$coef[3])

plot(y ~ x, main = "Logistic Function", xlab=ind, ylab=dep)
lines(0:max(x), predict(log.ss, data.frame(x=0:max(x))), col="red")

r1 <- sum((x - mean(x))^2)
r2 <- sum(residuals(log.ss)^2)

r_sq <- (r1 - r2) / r1

out <- data.frame(cbind(c(C=C, a=A, k=K, R.value=sqrt(r_sq))))
names(out)[1] <- "Logistic Curve"

return(out)
}

-