从混合模型(lme4)公式中提取成分 [英] Extract components from mixed model (lme4) formula

查看:93
本文介绍了从混合模型(lme4)公式中提取成分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用R编写一个函数,该函数接受如下公式:

I'm trying to write a function in R that accepts a formula such as the following:

y ~ 1 + sex + age + (1 | school) + (1 | school:section)

是否有一种简单的方法可以提取此公式的各种成分以用于我的函数中?例如,我希望能够获得左侧,每个变量,随机效果变量及其嵌套方式等.

Is there an easy way to extract the various components of this formula for use in my function? For example, I would like to be able to get the left hand side, each of the variables, the random effects variables and how they are nested, etc.

有没有比遍历公式分析树更简单的方法了?

Is there an easier way to do this than walking the formula parse tree?

推荐答案

如果您想要不需要正则表达式的解决方案,建议您考虑terms.

If you want a solution which doesn't require regex, I suggest you consider 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从其中提取属性:

Furthermore you can extract attributes from it using attributes:

attributes(terms(form))$term.labels

## [1] "sex"                "age"                "1 | school"         "1 | school:section"

这篇关于从混合模型(lme4)公式中提取成分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆