【发布时间】:2019-04-05 12:11:11
【问题描述】:
我继承了一些代码,这些代码使用了我认为是库的常见 R 习惯用法,但我不确定以这种冗长的方式编写会实现什么。最终我打算重写,但我想先知道为什么,然后再做一些愚蠢的事情。
ecd <-
function(formula, data, subset, weights, offset, ...) {
cl = match.call()
mf = match.call(expand.dots = FALSE)
m =
match(c("formula", "data", "subset", "weights", "offset"),
names(mf),
0L)
mf = mf[c(1L, m)]
mf$drop.unused.levels = TRUE
mf[[1L]] = quote(stats::model.frame)
mf = eval(mf, parent.frame())
mt = attr(mf, "terms")
y = stats::model.response(mf, "numeric")
w = as.vector(stats::model.weights(mf))
offset = as.vector(stats::model.offset(mf))
x = stats::model.matrix(mt, mf, contrasts)
z = ecd.fit(x, y, w, offset, ...)
我目前的理解是它从函数的原始参数构造一个函数调用对象(类型?)然后手动调用它,而不是直接调用stats::model.frame。任何见解将不胜感激。
【问题讨论】:
-
eval(mf,parent.frame())正在从合适的环境中获取mf。 -
我以为是在父环境中调用
mf,不是吗? -
eval evaluates the expr argument in the environment specified by envir and returns the computed value. If envir is not specified, then the default is parent.frame() (the environment where the call to eval was made).来自文档 (help("eval"))。 -
是的,所以它在父环境中评估
mf,它以通常的方式获取mf(作为封闭框架的函数参数),然后返回在父框架中评估mf的值(然后将其分配给一个名为mf的变量......好吧,我没有写这个)。当然,除非“获取mf”是指分配变量(“新”mf),在这种情况下我认为我们是一致的。
标签: r