broom Exercises in R: 15 Practice Problems
Fifteen practice problems on broom: tidy, glance, augment for common R models. Hidden solutions.
RRun this once before any exercise
library(broom)
library(dplyr)
library(purrr)
library(tidyr)
Exercise 1: tidy lm
Difficulty: Beginner.
Show solution
RInteractive R
fit <- lm(mpg ~ wt, data = mtcars)
tidy(fit)
Exercise 2: tidy with CI
Difficulty: Intermediate.
Show solution
RInteractive R
fit <- lm(mpg ~ wt, data = mtcars)
tidy(fit, conf.int = TRUE)
Exercise 3: glance lm
Difficulty: Intermediate.
Show solution
RInteractive R
fit <- lm(mpg ~ wt, data = mtcars)
glance(fit)
Exercise 4: augment lm
Difficulty: Intermediate.
Show solution
RInteractive R
fit <- lm(mpg ~ wt, data = mtcars)
augment(fit) |> head()
Exercise 5: tidy glm with exponentiate
Difficulty: Intermediate.
Show solution
RInteractive R
fit <- glm(am ~ mpg, data = mtcars, family = binomial)
tidy(fit, exponentiate = TRUE, conf.int = TRUE)
Exercise 6: tidy t.test
Difficulty: Intermediate.
Show solution
RInteractive R
tidy(t.test(mpg ~ am, data = mtcars))
Exercise 7: tidy cor.test
Difficulty: Intermediate.
Show solution
RInteractive R
tidy(cor.test(mtcars$wt, mtcars$mpg))
Exercise 8: tidy chisq.test
Difficulty: Intermediate.
Show solution
RInteractive R
tidy(chisq.test(table(mtcars$cyl, mtcars$am)))
Exercise 9: tidy aov
Difficulty: Intermediate.
Show solution
RInteractive R
tidy(aov(Sepal.Length ~ Species, data = iris))
Exercise 10: tidy survival fit
Difficulty: Advanced.
Show solution
RInteractive R
library(survival)
tidy(coxph(Surv(time, status) ~ age, data = lung))
Exercise 11: Many models with broom
Difficulty: Advanced.
Show solution
RInteractive R
iris |>
group_by(Species) |>
tidyr::nest() |>
mutate(model = purrr::map(data, ~ lm(Sepal.Length ~ Petal.Length, .x)),
tidy = purrr::map(model, tidy)) |>
tidyr::unnest(tidy)
Exercise 12: glance per group
Difficulty: Advanced.
Show solution
RInteractive R
iris |>
group_by(Species) |>
tidyr::nest() |>
mutate(model = purrr::map(data, ~ lm(Sepal.Length ~ Petal.Length, .x)),
glance = purrr::map(model, glance)) |>
tidyr::unnest(glance) |>
select(Species, r.squared)
Exercise 13: augment + residual plot
Difficulty: Intermediate.
Show solution
RInteractive R
fit <- lm(mpg ~ wt, data = mtcars)
aug <- augment(fit)
plot(aug$.fitted, aug$.resid)
abline(h = 0)
Exercise 14: tidy kmeans
Difficulty: Advanced.
Show solution
RInteractive R
set.seed(1)
km <- kmeans(iris[, 1:4], 3)
tidy(km)
Exercise 15: glance kmeans
Difficulty: Intermediate.
Show solution
RInteractive R
set.seed(1)
km <- kmeans(iris[, 1:4], 3)
glance(km)
What to do next
- Linear-Regression-Exercises (shipped), broom + lm in detail.
- Machine-Learning-Exercises (shipped), broom + tidymodels.