Search code examples
rregressionexponentialnls

Calculate the values of A and B from the estimated equation y = A * exp(x * B)


So I ran this code to generate the x and y values for an exponential curve I was estimating from a given data set:

qplot(x,y,data=dat) + stat_smooth(aes(outfit=fit1<<-..x..), 
      method = 'nls', method.args = list(start = c(a=1, b=0)), 
      formula = y~a*exp(b*x), se = FALSE)

qplot(x,y,data=dat) + stat_smooth(aes(outfit=fit2<<-..y..), 
      method = 'nls', method.args = list(start = c(a=1, b=0)), 
      formula = y~a*exp(b*x), se = FALSE)

That gave me the values of fit1 and fit2 or the list of values for the x and y axes of the curve. Now I want to use those two vectors of the x and y axes to estimate the values of A and B in the exponential equation used to predict them y=A*exp(B*x).

does this relatively easy with the following equations:

A=EXP(INDEX(LINEST(LN(B1:B10),A1:A10),1,2)) 
B=INDEX(LINEST(LN(B1:B10),$A$1:$A$10),1)

Is there a method or package that can replicate this in R? I've heard that easynls is one option but have had little success with it as it keeps returning an error stating:

My code: fit = dataframe(fit1,fit2)
nlsplot(fit, model=6, start=c(a=1, b=0))    

Error in nls(y ~ a * exp(b * x), start = list(a = s[1], b = s[2]), data = data, : number of iterations exceeded maximum of 6000

What I need is a way to read in the estimated values of x and y that I already have and then generate values for A and B given that the equation is an exponential format.

Example data:

fit1 = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
fit2 = c(.5, .45, .4, .35, .3, .25, .2, .15, .1, .05)

The purpose of this is to get the coefficients for the equation and then apply it as a function to other examples.


Solution

  • While agreeing with the comment of @JuliusVainora, the problem statement does not seem to have any restriction on the residuals. Here is a small example. Since you do not provide x,y data, I made some up.

    ## Example data
    set.seed(123)
    x = runif(25,0,2)
    y = 3.2 * exp(1.5*x) + rnorm(25, 0.1)
    
    ## Estimate A & B
    z = log(y)
    Model = lm(z ~ x)
    A = exp(Model$coefficients[1])
    B = Model$coefficients[2]
    
    ## Visual check of answer
    plot(x,y, pch=20)
    X2 = seq(0,2,0.1)
    Y2 = A*exp(B*X2)
    lines(X2, Y2, col="red")
    

    Exponential curve