knitr::opts_chunk$set(cache = TRUE, fig.align = "center", fig.width = 5, fig.height = 5,
                      cache.path = "./cache_knitr/Exo_pred/", fig.path = "./fig_knitr/Exo_pred/")

This is a simple example showing how to compute and plot predictions from a LM.

library(LM2GLMM) ## load the package

mod_UK1 <- lm(height ~ drink + sex*weight, data = UK)

range.weight.girls.fit <- range(mod_UK1$model$weight[mod_UK1$model$sex == "Girl"])
pred_all_cat <- expand.grid(drink  = levels(mod_UK1$model$drink),
                            sex    = "Girl",
                            weight = range.weight.girls.fit)
pred_all_cat$pred <- predict(mod_UK1, newdata = pred_all_cat)
pred_all_cat

range.height.girls.fit <- range(mod_UK1$model$height[mod_UK1$model$sex == "Girl"])

par(las = 1)
with(data = subset(mod_UK1$model, sex == "Girl" & drink == levels(drink)[1]),
     plot(height ~ weight, col = "orange", cex = 0.1, pch = ".",
          ylim = range.height.girls.fit, xlim = range.weight.girls.fit,
          xlab = "Girl's weight (Kg)", ylab = "Girl's height (cm)"))
with(data = subset(mod_UK1$model, sex == "Girl" & drink == levels(drink)[2]),
     points(height ~ weight, col = "red", cex = 0.1, pch = "."))
with(data = subset(mod_UK1$model, sex == "Girl" & drink == levels(drink)[3]),
     points(height ~ weight, col = "green", cex = 0.1, pch = "."))
with(data = subset(mod_UK1$model, sex == "Girl" & drink == levels(drink)[4]),
     points(height ~ weight, col = "yellow", cex = 0.1, pch = "."))

points(subset(pred_all_cat, drink == levels(drink)[1])$pred
       ~ range.weight.girls.fit, type = "l", lwd = 3, col = "orange")
points(subset(pred_all_cat, drink == levels(drink)[2])$pred
       ~ range.weight.girls.fit, type = "l", lwd = 3, col = "red")
points(subset(pred_all_cat, drink == levels(drink)[3])$pred
       ~ range.weight.girls.fit, type = "l", lwd = 3, col = "green")
points(subset(pred_all_cat, drink == levels(drink)[4])$pred
       ~ range.weight.girls.fit, type = "l", lwd = 3, col = "yellow")

legend("bottomright", fill = c("orange", "red", "green", "yellow")[c(3 , 4, 1, 2)],
       legend = levels(subset(mod_UK1$model, sex == "Girl")$drink)[c(3 , 4, 1, 2)], bty = "n")


courtiol/LM2GLMM documentation built on July 3, 2022, 7:42 a.m.