library(LM2GLMM) knitr::opts_chunk$set(cache = FALSE, fig.align = "center", fig.width = 4, fig.height = 4, cache.path = "./cache_knitr/Exo_LM_intro/", fig.path = "./fig_knitr/Exo_LM_intro/") options(width = 110) set.seed(1L)
If the average IQ for boys were 90 and 110 for girls, what would the parameter values be, for each of the following alternative coding for a boy and a girl (using treatment contrasts):
"boy"
vs "girl"
"male"
vs "female"
0
vs 1
1
vs 2
TRUE
vs FALSE
Are these different representations of ages equivalent?
"baby"
vs "child"
vs "adult"
0
vs 1
vs 2
1
vs 2
vs 3
Turn the following code into a function that takes the number of aliens to generate as an argument:
Tip: Remember to check ?sample()
to understand what this new function does.
Alien <- data.frame(humans_eaten = sample(1:3, size = 6, replace = TRUE), intercept = 50, slope = 1.5) Alien$error <- rnorm(n = 6, mean = 0, sd = sqrt(5)) Alien$size <- Alien$intercept + Alien$slope*Alien$humans_eaten + Alien$error
Adapt the following code to include an interaction between sex
and bh_trips
.
set.seed(123) Alien2 <- data.frame(planet = factor(c(rep("Chambr", 2), rep("Riplyx", 2), rep("Wickor", 2))), sex = factor(rep(c("Z", "ZZ"), times = 3)), bh_trips = 6:1) Alien2$age <- rep(0, nrow(Alien2)) Alien2$age[Alien2$planet == "Chambr"] <- Alien2$age[Alien2$planet == "Chambr"] + 100 Alien2$age[Alien2$planet == "Riplyx"] <- Alien2$age[Alien2$planet == "Riplyx"] + 1000 Alien2$age[Alien2$planet == "Wickor"] <- Alien2$age[Alien2$planet == "Wickor"] + 10000 Alien2$age[Alien2$sex == "Z"] <- Alien2$age[Alien2$sex == "Z"] + -20 Alien2$age[Alien2$sex == "ZZ"] <- Alien2$age[Alien2$sex == "ZZ"] + 20 Alien2$age <- Alien2$age + 0.5*Alien2$bh_trips Alien2$age <- Alien2$age + rnorm(nrow(Alien2), mean = 0, sd = 4) Alien2
Start by fitting this model:
fit_UK1 <- lm(height ~ drink + sex*weight, data = UK)
Note: for information on this dataset, check the details section in ?UK
.
fit_UK1
Compute the following predictions by (1) creating a design matrix by hand & (2) using the function predict()
:
newX <- matrix( c(1, 1, 0, 0, 0, 30, 0, 1, 1, 0, 0, 1, 30, 30, 1, 0, 0, 0, 0, 35, 0), nrow = 3, byrow = TRUE) colnames(newX) <- names(coef(fit_UK1)) newX %*% coef(fit_UK1)
newdata1 <- data.frame( drink = c("Most days", "Most days", "2 to 3 times a week"), sex = c("Boy", "Girl", "Boy"), weight = c(30, 30, 35)) predict(fit_UK1, newdata = newdata1)
fit_UK1
data.frame(coef(fit_UK1))
What do each of these estimates really mean?
(If you struggle interpreting parameter estimates, look at the fitted values)
fit_UK1
Create a plot with predictions showing the influence of the weight of girls on their height!
Tip: Look back at slides about predictions to work out how to deal with the effect of 'drink'.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.