Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract just the random effects part of the formula from lme4

Tags:

r

lme4

Let us say I have fitted a model such

mymodel <- lmer(Y~X1+(1|fac1)+(1|fac2),mydata)

How can I extract just the random effects part of the formula ((1|fac1)+(1|fac2)) ?

I know I can do

formula(mymodel)[-2]

but this just returns X1 + (1| fac1) + (1| fac2)

I know I could do something with regex but I was hoping there was an easier way.

like image 579
Robert Long Avatar asked Jul 18 '20 09:07

Robert Long


People also ask

How do you calculate fixed and random effects?

The most important practical difference between the two is this: Random effects are estimated with partial pooling, while fixed effects are not. Partial pooling means that, if you have few data points in a group, the group's effect estimate will be based partially on the more abundant data from other groups.

What is difference between LMER and Glmer?

The lmer() function is for linear mixed models and the glmer() function is for generalized mixed models.


1 Answers

findbars

The lme4 package provides findbars:

library(lme4)

fo <- Y~X1+(1|fac1)+(1|fac2)

findbars(fo)
## [[1]]
## 1 | fac1
##
## [[2]]
## 1 | fac2

If character strings are needed we can use the following. deparse1 will handle certain uncommon cases that deparse fails at but deparse will mostly work as an alternative if it is necessary that this work in versions of R earlier than R 4.0.0.

sapply(findbars(fo), deparse1)
## [1] "1 | fac1" "1 | fac2"

If the desired result is the RHS of the formula but without the fixed effects terms then we can reconstitute the above by adding back the parentheses and using reformulate. Omit [[2]] if a formula object is desired. Discussion above regarding deparse1 applies here too.

reformulate(sprintf("(%s)", sapply(findbars(fo), deparse1)))[[2]]
## (1 | fac1) + (1 | fac2)

terms/labels

Another way to get character result is to use labels which will extract them from terms . Use reformulate, as above, if a formula is desired. This does not use any packages.

X <- grep("|", labels(terms(fo)), fixed = TRUE, value = TRUE)
X
## [1] "1 | fac1" "1 | fac2"

As above, the formula and right hand side of it can be generated from X like this:

reformulate(sprintf("(%s)", X))
reformulate(sprintf("(%s)", X))[[2]]

getTerms

Another approach is to use getTerms from Terms of a sum in a R expression This short function recursively walks the formula to extract the terms. It does not use any packages.

XX <- grep("|", sapply(getTerms(fo[[3]]), deparse1), fixed = TRUE, value = TRUE)
XX
## [1] "(1 | fac1)" "(1 | fac2)"

The formula and right hand side of it can be generated like this:

reformulate(XX)
reformulate(XX)[[2]]
like image 97
G. Grothendieck Avatar answered Sep 28 '22 07:09

G. Grothendieck