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.
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.
The lmer() function is for linear mixed models and the glmer() function is for generalized mixed models.
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)
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]]
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With