#| include: false
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "man/figures/README-",
  out.width = "100%"
)

multilevelmod 3 nesting dolls on an orange background

Lifecycle: experimental Codecov test coverage R-CMD-check

multilevelmod enables the use of multi-level models (a.k.a mixed-effects models, Bayesian hierarchical models, etc.) with the parsnip package.

A sweaty Comic character trying to decide which button to push. The buttons read: 'mixed effect model', 'hierarchical linear model', 'random effects model', 'variance component model', 'mixed model', 'random intercepts/slopes', 'regularized regression', 'multilevel model', 'nested data model', and 'random parameter model'

(meme courtesy of @ChelseaParlett)

Installation

You can install the released version of multilevelmod from CRAN with:

install.packages("multilevelmod")

For the development version:

# install.packages("pak")
pak::pak("tidymodels/multilevelmod")

Available Engines

The multilevelmod package provides engines for the models in the following table.

#| echo: false
#| message: false
library(parsnip)

parsnip_models <- get_from_env("models") %>%
  setNames(., .) %>%
  purrr::map_dfr(get_from_env, .id = "model")

library(multilevelmod)

multilevelmod_models <- get_from_env("models") %>%
  setNames(., .) %>%
  purrr::map_dfr(get_from_env, .id = "model")

dplyr::anti_join(
  multilevelmod_models, parsnip_models, 
  by = c("model", "engine", "mode")
) %>%
  knitr::kable()

Example

Loading mixedlevelmod will trigger it to add a few modeling engines to the parsnip model database. For Bayesian models, there are now stan-glmer engines for linear_reg(), logistic_reg(), and poisson_reg().

To use these, the function parsnip::fit() function should be used instead of parsnip::fit_xy() so that the model terms can be specified using the lme/lme4 syntax.

The sleepstudy data is used as an example:

#| label: sleep-lme
library(multilevelmod)
set.seed(1234)
data(sleepstudy, package = "lme4")

mixed_model_spec <- linear_reg() %>% set_engine("lmer")

mixed_model_fit <- 
  mixed_model_spec %>% 
  fit(Reaction ~ Days + (Days | Subject), data = sleepstudy)

mixed_model_fit

For a Bayesian model:

#| label: sleep-stan
hier_model_spec <- linear_reg() %>% set_engine("stan_glmer")

hier_model_fit <- 
  hier_model_spec %>% 
  fit(Reaction ~ Days + (Days | Subject), data = sleepstudy)

hier_model_fit

Contributing

This project is released with a Contributor Code of Conduct. By contributing to this project, you agree to abide by its terms.



tidymodels/multilevelmod documentation built on Oct. 22, 2024, 10:21 a.m.