library(LM2GLMM)
knitr::opts_chunk$set(cache = TRUE, fig.align = "center", fig.width = 6, fig.height = 6,
                      cache.path = "./cache_knitr/Exo_Intro_solution/", fig.path = "./fig_knitr/Exo_Intro_solution/")
options(width = 90)

Computing with R

Instruction

Compute the following equation:

$\sqrt{\frac{2^{3+1}}{\frac{4}{5\times{6}}}-20}$

Solution

The idea is to do things step by step and always check that things are OK before they get too complex:

3+1
(3+1)
2^(3+1)
(2^(3+1)) / 4
(2^(3+1)) / (4 / (5*6))
((2^(3+1)) / (4 / (5*6))) - 20
sqrt(((2^(3+1)) / (4 / (5*6))) - 20)

Data exploration

Instruction

Using the dataset TitanicSurvival, figure out:

Solution

There are r nrow(TitanicSurvival) rows and r ncol(TitanicSurvival) columns:

dim(TitanicSurvival)

There are 3 factors:

str(TitanicSurvival)

To compute how many females below 20 years old survived in 2nd class and how many did not, you can do:

test <- TitanicSurvival[which(TitanicSurvival$sex == "female" &
                         TitanicSurvival$age < 20 &
                         TitanicSurvival$passengerClass == "2nd"), ]
table(test$survived)

Many other ways are possible, such as:

library(dplyr)
TitanicSurvival |>
  filter(sex == "female", age < 20, passengerClass == "2nd") |>
  count(survived)

An example of programming

Instruction

The following function can be used to investigate the statistical power of a t-test (i.e. the probability to detect a significant effect when they really is one = rate of true positive):

compare_heights <- function(n_group = 10, height_difference = 5) {
  male   <- rnorm(n = n_group, mean = 180, sd = 6)
  female <- rnorm(n = n_group, mean = 180 - height_difference, sd = 6)
  t_test_res <- t.test(male, female)
  t_test_res$p.value
}

N <- seq(from = 10, to = 60, by = 2)
power <- sapply(N, function(n) mean(replicate(100, compare_heights(n_group = n)) <= 0.05))
plot(power ~ N)

Can you run, read and understand this code?

Solution

I cannot really correct that one here. Ask me if you don't get it.

Plots

Instruction

Using the dataset TitanicSurvival, find a good way to show at once what influenced the survival of passengers.

Solution

coplot(survived ~ age | sex * passengerClass, data = TitanicSurvival, panel = panel.smooth)


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