Live code:

Live code
Linear regression
Published

February 23, 2023

library(tidyverse)
library(vegan) # install this in your Console: install.packages("vegan")
data(mite)
data(mite.env)
mite_dat <- mite.env %>%
  add_column(abundance = mite$LRUG)
# SLR
m1 <- lm(abundance ~ WatrCont, data = mite_dat)
summary(m1)

Call:
lm(formula = abundance ~ WatrCont, data = mite_dat)

Residuals:
    Min      1Q  Median      3Q     Max 
-16.525  -8.033  -4.088   4.493  47.937 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)  
(Intercept)  0.63410    4.51171   0.141   0.8886  
WatrCont     0.02385    0.01039   2.296   0.0248 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 12.29 on 68 degrees of freedom
Multiple R-squared:  0.07194,   Adjusted R-squared:  0.05829 
F-statistic: 5.271 on 1 and 68 DF,  p-value: 0.02477
# MLR
m2 <- lm(abundance ~ WatrCont + SubsDens, data = mite_dat)
summary(m2)

Call:
lm(formula = abundance ~ WatrCont + SubsDens, data = mite_dat)

Residuals:
    Min      1Q  Median      3Q     Max 
-20.192  -8.633  -1.385   6.866  44.245 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)   
(Intercept) 10.30549    5.48833   1.878  0.06477 . 
WatrCont     0.03444    0.01057   3.257  0.00177 **
SubsDens    -0.35682    0.12604  -2.831  0.00612 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 11.7 on 67 degrees of freedom
Multiple R-squared:  0.1711,    Adjusted R-squared:  0.1464 
F-statistic: 6.915 on 2 and 67 DF,  p-value: 0.001861
new_dat <- data.frame(WatrCont = 400:405, SubsDens = 30:35)
preds <- predict(m2, newdata = new_dat)
preds
       1        2        3        4        5        6 
13.37478 13.05239 12.73000 12.40761 12.08523 11.76284