如何捕获R公式中的固定术语?

6
假设我有带有随机项的 R 公式:
f1<-formula(y~x1+x2+(1|x3)+x1*x4)
f2<-formula(y~x1+x2+(1|x3+(0+x5|x3))+x1*x4)

我该如何仅获取这些公式的固定术语,以便满足以下要求:
fixterm
[1] "x1"    "x2"    "x4"    "x1:x4"
4个回答

4

这可能不完全符合您的要求,但它可能是有用的:

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

另一方面,如果你只想获取变量的名称,可以手动解析公式:
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"

这将为您提供与之几乎相同的结果。
all.vars(f1)
## [1] "y"  "x1" "x2" "x3" "x4"
all.vars(f2)
## [1] "y"  "x1" "x2" "x3" "x5" "x4"

但是它却给你一个提示,告诉你如何访问一些有趣的公式对象信息。

1
你可能只需要使用 grep 命令过滤掉非固定项。 - Rich Scriven

4
library(lme4)
f1.fixed <- terms(lme4:::nobars(f1))
attr(f1.fixed, "term.labels")
#[1] "x1"    "x2"    "x4"    "x1:x4"

2

使用grep命令可以去除非固定项,从而得到唯一的术语。执行unique(ft)命令可以显示只在f1f2中独有的固定项。

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

1
最简单的方法是使用lme4包:
# require(lme4)
f1 <- formula(y~x1+x2+(1|x3)+x1*x4)
f2 <- formula(y~x1+x2+(1|x3+(0+x5|x3))+x1*x4)

# extracting random terms
findbars(f1); findbars(f2) 

# [[1]]
# 1 | x3
# [[1]]
# 1 | x3 + (0 + x5 | x3)

# extracting fixed terms
nobars(f1); nobars(f2) 

# y ~ x1 + x2 + x1 * x4
# y ~ x1 + x2 + x1 * x4

而且你可以用很少的代码实现这个!:-)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接