Functional Programming

Functionals, Function Factories, and Function Operators

Author

Brian Helsel

Published

October 7, 2026

Assignment. Practice using functionals, function factories, and function operators to improve your programming skillset.

Functionals: Run Multiple Regressions. Use a functional to fit a separate regression of mpg on each predictor. Extract the coefficient, p-value, and R2 from each model. Combine the results into a data frame showing one row per predictor.

predictors <- c("disp", "hp", "wt", "qsec")

models <- purrr::map(predictors, \(x) {
  lm(reformulate(x, response = "mpg"), data = mtcars)
})

purrr::map_dfr(models, \(model) {
  broom::tidy(model) |>
    dplyr::filter(term != "(Intercept)") |>
    dplyr::select(term, estimate, p.value) |>
    dplyr::mutate(r_squared = broom::glance(model)$r.squared)
})
# A tibble: 4 × 4
  term  estimate  p.value r_squared
  <chr>    <dbl>    <dbl>     <dbl>
1 disp   -0.0412 9.38e-10     0.718
2 hp     -0.0682 1.79e- 7     0.602
3 wt     -5.34   1.29e-10     0.753
4 qsec    1.41   1.71e- 2     0.175

Function Factories: Create a Model Factory. Create a function called make_modeler that takes a dataset and an outcome variable and returns a function that fits a linear model using a predictor supplied later. Use it to fit models predicting mpg and modify the returned function so it returns a tidy summary of the model rather than the entire model object.

make_modeler <- function(data, outcome) {
  function(predictor) {
    model <- lm(reformulate(predictor, response = outcome), data = data)
    tidymodel <- broom::tidy(model) |>
      dplyr::filter(term != "(Intercept)")
    return(tidymodel)
  }
}

model_mpg <- make_modeler(mtcars, "mpg")

purrr::map_dfr(predictors, model_mpg)
# A tibble: 4 × 5
  term  estimate std.error statistic  p.value
  <chr>    <dbl>     <dbl>     <dbl>    <dbl>
1 disp   -0.0412   0.00471     -8.75 9.38e-10
2 hp     -0.0682   0.0101      -6.74 1.79e- 7
3 wt     -5.34     0.559       -9.56 1.29e-10
4 qsec    1.41     0.559        2.53 1.71e- 2