Are random effect variables automatically taken as factors in lmer (or lme) in R?

I understand that having a continuous or numerical variable as a random effect in a mixed effects model does not make much sense (for example, see here ).

But I wonder if lme4::lmeror nlme::lmein R purposefully prevents you from doing this ...

In particular, I ask: if I put lmer(or lme) any non-factorial (non-categorical) variable as a random effect, does the function automatically process it as a factor?

Inserting factor()directly into lmer (as commonly used when using it lm) causes the following error:

lmer(y ~ z + (1|factor(x)), data = dat)
Error: couldn't evaluate grouping factor factor(x) within model frame: try adding grouping factor to data frame explicitly if possible

Although the above error mentions adding a grouping factor directly to the data, it does not indicate whether the grouping factor should be a factor (or perhaps implied from a word choice)?

I understand that it is quite simple to create a new factor class variable directly from my data, but I'm just wondering if this is really necessary when using lmer(or lme).

+4
source share
1 answer

It does not matter.

library(lme4)

sl <- sleepstudy
sl$Subject <- as.numeric(levels(sl$Subject))[sl$Subject]

## subject as factor
m1 <- lmer(Reaction ~ Days + (1|Subject), data = sleepstudy)

## subject as numeric
m2 <- update(m1, data = sl)

all.equal(VarCorr(m1), VarCorr(m2))
# TRUE

By checking the rest of the object, the call is different (which makes sense, I called the data frame something else), and the frame is different (due to the difference between the numbers and factors in the subject). Everything else is identical.

all.equal(m1, m2)
#[1] "Attributes: < Component "call": target, current do not match when deparsed >"     
#[2] "Attributes: < Component "frame": Component "Subject": 'current' is not a factor >"

factorize() mkBlist(), mkReTrms(), . factorize() , factor(x) ( , ..)

+2

Source: https://habr.com/ru/post/1657302/


All Articles