Search code examples
rnon-linear-regression

How to do multiple polynomial regression in R?


To do a [muliple] linear regression model, one uses lm

Is it possible to derive a multiple polynomial regression model? Where each coefficient is a polynomial function?


Solution

  • You can do it, please see an example below. Just add in poly function argument raw = TRUE to get easily interpretable coefficients:

    set.seed(123)
    
    x <- seq(-10, 10, by = 0.1)
    y <- 0.5 * x ^ 3 + rnorm(length(x), 0, sd = 10)
    
    df <- data.frame(x, y)
    
    m <- lm(y ~ poly(x,3, raw = TRUE), data = df)
    summary(m)
    
    # Coefficients:
    #   Estimate Std. Error t value Pr(>|t|)    
    # (Intercept)             -0.337708   1.015189  -0.333    0.740    
    # poly(x, 3, raw = TRUE)1 -0.156641   0.291625  -0.537    0.592    
    # poly(x, 3, raw = TRUE)2  0.010747   0.022476   0.478    0.633    
    # poly(x, 3, raw = TRUE)3  0.501871   0.004411 113.783   <2e-16 ***
    #  ---
    #  Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
    
    plot(df$x, df$y, col = "blue", xlab = "x", ylab = "y")
    df$fitted <- fitted(m, data.frame(x))
    lines(df$x, df$fitted, col = "red", lwd = 2)
    

    Output (red line is fitted data, blue dots are initial data):

    enter image description here