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]]