如何从公式对象中可靠地获取因变量名?

Ada*_*ski 36 r

假设我有以下公式:

myformula<-formula("depVar ~ Var1 + Var2")
Run Code Online (Sandbox Code Playgroud)

如何从公式对象中可靠地获取因变量名?

我找不到任何用于此目的的内置函数.我知道这样as.character(myformula)[[2]]可行

sub("^(\\w*)\\s~\\s.*$","\\1",deparse(myform))
Run Code Online (Sandbox Code Playgroud)

在我看来,这些方法更像是一种hackery,而不是一种可靠而标准的方法.


有没有人知道如何使用的确切方法lm?我已经看过它的代码,但对我来说有点神秘...这里有一个方便的引用:

    > lm
function (formula, data, subset, weights, na.action, method = "qr", 
    model = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE, 
    contrasts = NULL, offset, ...) 
{
    ret.x <- x
    ret.y <- y
    cl <- match.call()
    mf <- match.call(expand.dots = FALSE)
    m <- match(c("formula", "data", "subset", "weights", "na.action", 
        "offset"), names(mf), 0L)
    mf <- mf[c(1L, m)]
    mf$drop.unused.levels <- TRUE
    mf[[1L]] <- as.name("model.frame")
    mf <- eval(mf, parent.frame())
    if (method == "model.frame") 
        return(mf)
    else if (method != "qr") 
        warning(gettextf("method = '%s' is not supported. Using 'qr'", 
            method), domain = NA)
    mt <- attr(mf, "terms")
    y <- model.response(mf, "numeric")
    w <- as.vector(model.weights(mf))
    if (!is.null(w) && !is.numeric(w)) 
        stop("'weights' must be a numeric vector")
    offset <- as.vector(model.offset(mf))
    if (!is.null(offset)) {
        if (length(offset) != NROW(y)) 
            stop(gettextf("number of offsets is %d, should equal %d (number of observations)", 
                length(offset), NROW(y)), domain = NA)
    }
    if (is.empty.model(mt)) {
        x <- NULL
        z <- list(coefficients = if (is.matrix(y)) matrix(, 0, 
            3) else numeric(), residuals = y, fitted.values = 0 * 
            y, weights = w, rank = 0L, df.residual = if (!is.null(w)) sum(w != 
            0) else if (is.matrix(y)) nrow(y) else length(y))
        if (!is.null(offset)) {
            z$fitted.values <- offset
            z$residuals <- y - offset
        }
    }
    else {
        x <- model.matrix(mt, mf, contrasts)
        z <- if (is.null(w)) 
            lm.fit(x, y, offset = offset, singular.ok = singular.ok, 
                ...)
        else lm.wfit(x, y, w, offset = offset, singular.ok = singular.ok, 
            ...)
    }
    class(z) <- c(if (is.matrix(y)) "mlm", "lm")
    z$na.action <- attr(mf, "na.action")
    z$offset <- offset
    z$contrasts <- attr(x, "contrasts")
    z$xlevels <- .getXlevels(mt, mf)
    z$call <- cl
    z$terms <- mt
    if (model) 
        z$model <- mf
    if (ret.x) 
        z$x <- x
    if (ret.y) 
        z$y <- y
    if (!qr) 
        z$qr <- NULL
    z
}
Run Code Online (Sandbox Code Playgroud)

sea*_*ody 36

尝试使用all.vars:

all.vars(myformula)[1]
Run Code Online (Sandbox Code Playgroud)

  • 这个变体不依赖于`all.vars`变量的返回顺序:`all.vars(update(myformula,.~1))`. (8认同)
  • 无需更新公式:`all.vars(myformula [[2]])`工作得很好. (5认同)
  • 请注意,`all.vars(~b + c)`会给你不正确的结果. (2认同)

Rei*_*son 13

我想你也可以自己做功能terms():

getResponse <- function(formula) {
    tt <- terms(formula)
    vars <- as.character(attr(tt, "variables"))[-1] ## [1] is the list call
    response <- attr(tt, "response") # index of response var
    vars[response] 
}

R> myformula <- formula("depVar ~ Var1 + Var2")
R> getResponse(myformula)
[1] "depVar"
Run Code Online (Sandbox Code Playgroud)

它就像hacky一样,as.character(myformyula)[[2]]但你可以保证得到正确的变量,因为调用解析树的顺序不会很快改变.

多个因变量不太好:

R> myformula <- formula("depVar1 + depVar2 ~ Var1 + Var2")
R> getResponse(myformula)
[1] "depVar1 + depVar2"
Run Code Online (Sandbox Code Playgroud)

因为他们需要进一步处理.


Gao*_*Hao 13

我找到了一个有用的包'formula.tools',它适合你的任务.

代码示例:

f < - as.formula(a1 + a2~a3 + a4)

lhs.vars(f)#get因变量

[1]"a1""a2"

rhs.vars(f)#get自变量

[1]"a3""a4"


Rei*_*son 6

基于您的编辑以获得实际响应,而不仅仅是其名称,我们可以使用lm()基准R中的公式接口使用的非标准评估惯用法和大多数其他建模函数

form <- formula("depVar ~ Var1 + Var2")
dat <- data.frame(depVar = rnorm(10), Var1 = rnorm(10), Var2 = rnorm(10))

getResponse <- function(form, data) {
    mf <- match.call(expand.dots = FALSE)
    m <- match(c("formula", "data"), names(mf), 0L)
    mf <- mf[c(1L, m)]
    mf$drop.unused.levels <- TRUE
    mf[[1L]] <- as.name("model.frame")
    mf <- eval(mf, parent.frame())
    y <- model.response(mf, "numeric")
    y
} 

> getResponse(form, dat)
          1           2           3           4           5 
-0.02828573 -0.41157817  2.45489291  1.39035938 -0.31267835 
          6           7           8           9          10 
-0.39945771 -0.09141438  0.81826105  0.37448482 -0.55732976
Run Code Online (Sandbox Code Playgroud)

如您所见,这将从提供​​的数据框中获取实际的响应变量数据.

这是如何工作的,该函数首先捕获函数调用而不扩展...参数,因为它包含评估公式数据所不需要的东西.

接下来,"formula""data"参数与调用匹配.该行mf[c(1L, m)]从call(1L)中选择函数名称以及两个匹配参数的位置.该drop.unused.levels的参数model.frame()被设置为TRUE在下一行,然后呼叫更新从调用切换函数名lmmodel.frame.上面的所有代码都是将调用lm()和进程调用调用到model.frame()函数的调用.

然后在函数的父环境中评估此修改的调用 - 在本例中是全局环境.

最后一行使用model.response()提取器函数从模型框架中获取响应变量.