I'm trying to write a function for fitting a logistic curve using nls with the self-starting option ssLogis. I've got some data - which will actually come as a data frame, so this first step is really just to get a similar data set-up to what I'll be working with...
int <- c(.1, .2, .5, .8, 1.5, 2.5, 4.1, 6.1, 8.8, 13.8, 25.5, 29.2, 35, 37.9, 41.4)
yr2 <- 1:15
newdata <- data.frame(int, yr2)
So, onto the function I've written - with the help of Fox & Weisberg...
log.fit <- function(dep, ind, yourdata){
#Self-starting...
log.ss <- nls(dep ~ SSlogis(ind, phi1, phi2, phi3), data=yourdata)
#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(dep ~ ind, data=yourdata, main = "Logistic Function", xlab=ind, ylab=dep)
with(data, lines(seq(0, max(ind), 1), predict(log.ss, data.frame(ind=seq(0,max(ind),1)))))
p <- (yourdata$ind)
m <- mean(p)
r1 <- sum((p-m)^2)
r2 <- sum(residuals(log.ss)^2)
r_sq <- (r1-r2) / r1
R <- sqrt(r_sq)
return(c(C=C, a=A, k=K, R.value=R))
}
I can't even get out of the blocks with this to see if the rest of my function code is OK...I get an error when I run the function:
log.fit(int, yr2, newdata)
Then, I get this error:
Error in SSlogis(ind, phi1, phi2, phi3) : object 'phi2' not found
phi2 is a parameter that is estimated with ssLogis, so I'm lost. This runs like a champ outside the function.