Solved – Fitting a function with R

curve fittingnlsr

I want to fit a function to these data:

s <- c(20:60)
I <- c(0, 0.007515662, 0.015878514, 0.024994325, 0.034728341, 0.044910579, 0.055344590, 
       0.065818599, 0.076118441, 0.086040566, 0.095403934, 0.104059903, 0.111898792, 
       0.118853016, 0.124896650, 0.130041857, 0.134332925, 0.137838655, 0.140644404,  
       0.142844161, 0.144533652, 0.145804788, 0.146741667, 0.147418108, 0.147896553, 
       0.148228057, 0.148453067, 0.148602679, 0.148700131, 0.148762313, 0.148801181, 
       0.148824980, 0.148839256, 0.148847645, 0.148852473, 0.148855195, 0.148856698, 
       0.148857511, 0.148857941, 0.148858164, 0.148858276)

The plot is the following:

enter image description here

I tried using nls as follows:

mod <- nls(I~exp(a+b*s), start=list(a=0, b=0))

but I think I got a bad fit.

This is the fit I got by nls method with these initial parameters:

(RSS.p <- sum(residuals(mod)^2))  # Residual sum of squares
(TSS <- sum((I - mean(I))^2))  # Total sum of squares
1 - (RSS.p/TSS)  # R-squared measure
0.611088

enter image description here

I am interesting in finding an expression for a function with parameters, not only in a good graphical fit (because then I want to treat this function analytically).

Best Answer

You could try adding a constant term c and a negative sign to your original equation, plus an additional squared term, as suggested by other answers:

mod <- nls(I ~ c - exp(a + b*s + d*s^2), start=list(c = 0.15, a = 0.4, b = -0.1, d = 0))

to obtain such fit:

enter image description here