Suppose I have R formulas with random terms:
f1<-formula(y~x1+x2+(1|x3)+x1*x4)
f2<-formula(y~x1+x2+(1|x3+(0+x5|x3))+x1*x4)
how could I just get the fixed terms of these formulas such that:
fixterm
[1] "x1" "x2" "x4" "x1:x4"
library(lme4)
f1.fixed <- terms(lme4:::nobars(f1))
attr(f1.fixed, "term.labels")
#[1] "x1" "x2" "x4" "x1:x4"
This is not exactly what you are looking for, but it may be useful:
> attr(terms(f1),"term.labels")
[1] "x1" "x2" "1 | x3" "x4" "x1:x4"
> attr(terms(f2),"term.labels")
[1] "x1" "x2" "1 | x3 + (0 + x5 | x3)"
[4] "x4" "x1:x4"
On the other hand, If you'd like to get only the names of variables, you may deparse the formula manually:
reclapply <- function(x) {
if (is.name(x)) as.character(x)
else if (is.atomic(x)) NULL # ignore
else lapply(2:length(x), # omit function name - 1st element
function(i) reclapply(x[[i]]))
}
unique(unlist(reclapply(f1[[3]])))
## [1] "x1" "x2" "x3" "x4"
unique(unlist(reclapply(f2[[3]])))
## [1] "x1" "x2" "x3" "x5" "x4"
This gives you almost the same result as
all.vars(f1)
## [1] "y" "x1" "x2" "x3" "x4"
all.vars(f2)
## [1] "y" "x1" "x2" "x3" "x5" "x4"
but provides you with a hint on how to access some interesting information on the formula object.
It seems we can get the unique terms by using grep
to remove the non-fixed terms. The result of unique(ft)
shows the fixed terms that are unique to both f1
and f2
> ft <- unlist(lapply(c(f1, f2), function(x){
grep("\\|", attr(terms(x), "term.labels"), invert = TRUE, value = TRUE)
}))
> unique(ft)
## [1] "x1" "x2" "x4" "x1:x4"
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