How to extract the original formula (fixed-effects and random-effects) from an lmerMod object?

Suppose we have postulated the following linear mixed model (LMM), which we generically call fit.

library(lme4)

fit <- lmer(Reaction ~ Days + (1 | Subject), data = sleepstudy)

Suppose that we are also interested in extracting the original formula (i.e. both the fixed-effects and random-effects part) from fit, which we would like to pass to a second LMM termed fit2. Obviously, passing terms(fit) to the formula argument of lmer() does not work.

> fit2 <- lmer(terms(fit), data = sleepstudy)
Error: No random effects terms specified in formula

Question

Is there a way to extract both fixed-effects and random-effects part from fit, which can then be passed to lmer()?


Solution 1:

It is standard for packages like lme4 to implement formula methods whose sole purpose is to extract formula(e) from model objects, so that you don't have to think too much about object internals.

In lme4, there is a formula method for class "merMod", namely lme4:::formula.merMod. There is no method for class "lmerMod", but since "lmerMod" is a direct subclass of "merMod"—you can check with showClass("lmerMod")—the method for "merMod" is called whenever you do formula(<lmerMod>).

Hence:

formula(fit)
## Reaction ~ Days + (1 | Subject)
formula(fit, fixed.only = TRUE)
## Reaction ~ Days
formula(fit, random.only = TRUE)
## Reaction ~ (1 | Subject)
## <environment: 0x11b3944e0>

(The last call returns a formula whose environment is not what it should be. I've created an issue on GitHub.)

lme4 implements a number of extraction methods for class "merMod". For example, there is also a model.matrix method that you can use to extract fixed and random effect model matrices. Most of these methods are documented in ?lme4::`merMod-class`, so you can use that a reference in the future.

For a complete list of available methods, just look at

methods(class = "merMod")
methods(class = "lmerMod")

after loading lme4.