if (FALSE) {
library(dplyr)
medData <- medication |>
filter(time %% 1 == 0, time < 4)
bootFun <- function(d) lm(pos ~ treat*time, data = d)$coefficients
# Resampling on the person level only
clusterBootstrap(df = medData,
clusters = "id",
replace = TRUE,
stat_fun = bootFun,
B = 5000)
# Resampling on the person level and the repeated measures level
clusterBootstrap(df = medData,
clusters = c("id", "time"),
replace = c(TRUE, TRUE),
stat_fun = bootFun,
B = 5000)
# Not resampling at one level
# (e.g., by design all classes in a probed school are included,
# but not all students in a class)
set.seed(2025)
n_school <- 30
n_class <- 8
n_student <- 15
demo <- expand.grid(
school = paste0("S", 1:n_school),
class = paste0("C", 1:n_class),
student = paste0("P", 1:n_student)) |>
mutate(score1 = rnorm(n()),
score2 = rnorm(n())) |>
arrange(school, class, student) |>
slice(1:(n() - 3)) # slightly unbalanced data
bootFun2 <- function(d) lm(score1 ~ score2, data = d)$coef
clusterBootstrap(df = demo,
clusters = c("school", "class", "student"),
replace = c(TRUE, FALSE, TRUE),
stat_fun = bootFun2,
B = 1000)
}
Run the code above in your browser using DataLab