rmodellmexponentiation

Get the A and B coefficients from exponential lm() model in R


I'm trying to get the A and B terms for an exponential model written as:

mod <- lm(log(y) ~ x)

When I call summary(mod), I understand I should take exp() of x to get B. What do I do with the intercept to get A so that I can write it in the form:

Y = A*B^x


Solution

  • In order to determine the coefficients of the linearized form of Y=AB^x, you need to know a little about log rules. First, we take the log of both sides, which gives log(Y)=log(AB^x). Multiplication with in a log is the same as addition, so we split A and B^x, log(Y)=log(A)+log(B^x). Lastly, exponentials in a log are the same as multiplication, so log(Y)=log(A)+xlog(B). This gives the general linear equation y=mx+b, where m = log(B), and b = log(A). When you run a linear regression, you need to calculate the A as exp(intercept) and B as exp(slope). Here is an example:

    library(tidyverse)
    
    example_data <- tibble(x = seq(1, 5, by = 0.1),
                           Y = 10*(4^{x}) +runif(length(x),min = -1000, max = 1000))
    
    example_data |>
      ggplot(aes(x, Y))+
      geom_point()
    

    model <- lm(log(Y) ~ x, data = example_data)
    
    summary(model)
    #> 
    #> Call:
    #> lm(formula = log(Y) ~ x, data = example_data)
    #> 
    #> Residuals:
    #>     Min      1Q  Median      3Q     Max 
    #> -1.9210 -0.3911  0.1394  0.3597  1.9107 
    #> 
    #> Coefficients:
    #>             Estimate Std. Error t value Pr(>|t|)    
    #> (Intercept)   3.6696     0.4061   9.036 2.55e-10 ***
    #> x             1.0368     0.1175   8.825 4.40e-10 ***
    #> ---
    #> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
    #> 
    #> Residual standard error: 0.7424 on 32 degrees of freedom
    #>   (7 observations deleted due to missingness)
    #> Multiple R-squared:  0.7088, Adjusted R-squared:  0.6997 
    #> F-statistic: 77.88 on 1 and 32 DF,  p-value: 4.398e-10
    
    A <- exp(summary(model)$coefficients[1,1]) #intercept
    B <- exp(summary(model)$coefficients[2,1]) #slope
    
    example_data |>
      ggplot(aes(x, Y))+
      geom_point()+
      geom_line(data = tibble(x = seq(1,5, by = 0.1),
                              Y = A*B^x), color = "blue") # plot model as check