Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture the fixed terms of a R formula?

Tags:

r

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"
like image 292
David Z Avatar asked Apr 21 '14 16:04

David Z


3 Answers

library(lme4)
f1.fixed <- terms(lme4:::nobars(f1))
attr(f1.fixed, "term.labels")
#[1] "x1"    "x2"    "x4"    "x1:x4"
like image 137
Roland Avatar answered Nov 20 '22 12:11

Roland


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.

like image 4
gagolews Avatar answered Nov 20 '22 12:11

gagolews


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"
like image 2
Rich Scriven Avatar answered Nov 20 '22 14:11

Rich Scriven