Search code examples
rcurve-fittingnls

How to fit a two-term exponential in R?


I would like to fit a two-term exponential model to my data given as (x,y), i.e.

f(x) = a * exp(b * x) + c * exp(d * x)

In essence, I need to replicate Matlab's exp2 model type in R calculated as

f = fit(x, y, 'expo')

Solution

  • This post does a good job explaining how to fit an abstract model like that. The jist of it is- use nls() to fit a "Nonlinear Least Squares" model:

    # Using the mpg data in ggplot2
    library(ggplot2)
    # Create list of initial estimates
    insertList = list(a=1,b=-0.01,c=1,d=-0.01)
    # fit model
    m1 = nls(displ ~ a*exp(b*cty) + c*exp(d*cyl),data =mpg, start = insertList)
    

    and the function should do the rest...

    The hard part is finding estimates to your model that will not give you an error when inputting this. The link provides insight into this. Good luck!

    Edit: Made the changes @Ben Bolker suggested; also, didn't realize mpg was in ggplot2 and not base R, thanks for the clarification.