我正在尝试在 R 中编写一个接受如下公式的函数:
y ~ 1 + sex + age + (1 | school) + (1 | school:section)
有没有一种简单的方法可以提取该公式的各个组成部分以在我的函数中使用?例如,我希望能够获取左侧、每个变量、随机效应变量以及它们的嵌套方式等。
有没有比遍历公式解析树更简单的方法?
最佳答案
如果您想要一个不需要正则表达式的解决方案,我建议您考虑terms
。
form <- y ~ 1 + sex + age + (1 | school) + (1 | school:section)
terms(form)
## y ~ 1 + sex + age + (1 | school) + (1 | school:section)
## attr(,"variables")
## list(y, sex, age, 1 | school, 1 | school:section)
## attr(,"factors")
## sex age 1 | school 1 | school:section
## y 0 0 0 0
## sex 1 0 0 0
## age 0 1 0 0
## 1 | school 0 0 1 0
## 1 | school:section 0 0 0 1
## attr(,"term.labels")
## [1] "sex" "age" "1 | school" "1 | school:section"
## attr(,"order")
## [1] 1 1 1 1
## attr(,"intercept")
## [1] 1
## attr(,"response")
## [1] 1
## attr(,".Environment")
## <environment: R_GlobalEnv>
此外,您可以使用attributes
从中提取属性:
attributes(terms(form))$term.labels
## [1] "sex" "age" "1 | school" "1 | school:section"
关于r - 从混合模型 (lme4) 公式中提取成分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14049440/