【发布时间】:2012-10-24 09:59:10
【问题描述】:
假设我有以下公式:
myformula<-formula("depVar ~ Var1 + Var2")
如何可靠地从公式对象中获取因变量名称?
我没有找到任何用于此目的的内置函数。
我知道as.character(myformula)[[2]] 和
sub("^(\\w*)\\s~\\s.*$","\\1",deparse(myform))
在我看来,这些方法更像是一种骇客,而不是一种可靠且标准的方法。
有谁知道究竟是什么方法,例如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
}
【问题讨论】:
-
您是否只有公式,或者您有拟合模型或编写的代码,使用这些公式接口的标准非标准评估规则? R 通常使用
terms组件来进行这种思考 -
@Gavin 不。我有一个公式之前计算模型。我正在编写一个用于引导的函数,它将用给定的残差替换 data.frame 中的因变量。我唯一可以得到 dep 名称的地方。变量是公式对象。如果我只是为了使用 $terms 组件来拟合模型,那将是非常浪费时间。
-
好的,我只记得
terms()也适用于公式,但处理该对象也会很麻烦而且很痛苦。我认为as.character(myformula)[[2]]是最不老套的——排序不会很快改变,我会冒险。 -
你编辑;这就是我的意思。
lm使用标准的非标准评估习语将公式与数据框对象匹配。您至少需要一个data参数加上其他一些参数,然后很容易获得模型框架并从中获得响应。 -
查看document (PDF),它解释了
lm()中所做的事情
标签: r