简体   繁体   English

从R中的模型中提取公式

[英]Extract formula from model in R

I'm building a function for many model types which needs to extract the formula used to make the model. 我正在为许多模型类型构建一个函数,需要提取用于制作模型的公式。 Is there a flexible way to do this? 有灵活的方法吗? For example: 例如:

x <- rnorm(10)
y <- rnorm(10)
z <- rnorm(10)
equation <- z ~ x + y
model <- lm(equation)

I what I need to do is extract the formula object "equation" once being passed the model. 我需要做的是在传递模型后提取公式对象“方程式”。

You could get what you wanted by: 你可以得到你想要的东西:

  model$call
# lm(formula = formula)

And if you want to see what I did find out then use: 如果你想看看我发现了什么然后使用:

str(model)

Since you passed 'formula' (bad choice of names by the way) from the calling environment you might then need to extract from the object you passed: 由于您从调用环境传递了'formula'(顺便选择名称),因此您可能需要从传递的对象中提取:

 eval(model$call[[2]])
# z ~ x + y

@JPMac offered a more compact method: formula(model) . @JPMac提供了一种更紧凑的方法: formula(model) It's also worth looking at the mechanism used by the formula.lm function. 还值得研究formula.lm函数使用的机制。 The function named formula is generic and you use methods(formula) to see what S3 methods have been defined. 名为formula的函数是通用的,您可以使用methods(formula)来查看已定义的S3方法。 Since the formula.lm method has an asterisk at its end, you need to wrap it in `getAnywhere: 由于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>

So it is using "$" to extract the list item named "formula" rather than pulling it from the call. 所以它使用“$”来提取名为“formula”的列表项,而不是从调用中提取它。 If the $formula item is missing (which it is in your case) then It then replaces that with formula(x$terms) which I suspect is calling formula.default and looking at the operation of that function appears to only be adjusting the environment of the object. 如果缺少$ formula项(它在你的情况下)然后它用formula(x$terms)替换它,我怀疑它是调用formula.default并且查看该函数的操作似乎只是调整环境对象。

As noted, model$call will get you the call that created the lm object, but if that call contains an object itself as the model formula, you get the object name, not the formula. 如上所述, model$call将为您创建创建lm对象的调用,但如果该调用包含对象本身作为模型公式,则获取对象名称,而不是公式。

The evaluated object, ie the formula itself, can be accessed in model$terms (along with a bunch of auxiliary information on how it was treated). 可以在model$terms访问评估对象(即公式本身)(以及关于如何处理它的一堆辅助信息)。 This should work regardless of the details of the call to lm . 无论调用lm的细节如何,这都应该有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM