我正在为许多模型类型构建一个函数,需要提取用于制作模型的公式.有灵活的方法吗?例如:
x <- rnorm(10)
y <- rnorm(10)
z <- rnorm(10)
equation <- z ~ x + y
model <- lm(equation)
Run Code Online (Sandbox Code Playgroud)
我需要做的是在传递模型后提取公式对象"方程式".
42-*_*42- 12
你可以得到你想要的东西:
model$call
# lm(formula = formula)
Run Code Online (Sandbox Code Playgroud)
如果你想看看我发现了什么然后使用:
str(model)
Run Code Online (Sandbox Code Playgroud)
由于您从调用环境传递了'formula'(顺便选择名称),因此您可能需要从传递的对象中提取:
eval(model$call[[2]])
# z ~ x + y
Run Code Online (Sandbox Code Playgroud)
@JPMac提供了一种更紧凑的方法:formula(model).值得一看的是该formula.lm函数使用的机制.名为的函数formula是通用的,您可以使用它methods(formula)来查看已定义的S3方法.由于该formula.lm方法的末尾有一个星号,您需要将其包装在`getAnywhere:
> getAnywhere(formula.lm)
A single object matching ‘formula.lm’ was found
It was found in the following places
registered S3 method for formula from namespace stats
namespace:stats
with value
function (x, ...)
{
form <- x$formula
if (!is.null(form)) {
form <- formula(x$terms)
environment(form) <- environment(x$formula)
form
}
else formula(x$terms)
}
<bytecode: 0x36ff26158>
<environment: namespace:stats>
Run Code Online (Sandbox Code Playgroud)
所以它使用"$"来提取名为"formula"的列表项,而不是从调用中提取它.如果缺少$ formula项(在你的情况下),那么然后它替换formula(x$terms)我怀疑正在调用的那个,formula.default并且查看该函数的操作似乎只是调整对象的环境.
如上所述,model$call将为您创建创建lm对象的调用,但如果该调用包含对象本身作为模型公式,则获取对象名称,而不是公式.
可以访问评估的对象,即公式本身model$terms(以及关于如何处理的一堆辅助信息).无论调用的详细信息如何,这都应该有效lm.
| 归档时间: |
|
| 查看次数: |
10766 次 |
| 最近记录: |