【发布时间】:2018-12-18 16:39:53
【问题描述】:
我正在尝试在 R 中编写自己的建模函数,它需要一个公式、一些数据,也许还有一些额外的上下文,比如权重;在调用model.frame 提取必要的数值数据后,它将执行拟合。我的第一关看起来像:
my_modfunc <- function(formula,data,weights=NULL) {
mf <- model.frame(formula,data=data,weights=weights)
wt <- model.weights(mf)
# do some fitting here...
}
# make fake data to test it
set.seed(1234)
data <- data.frame(x1=rnorm(50),x2=rnorm(50),y=rnorm(50),w=runif(50))
# call it:
my_modfunc(y ~ x1 + x2,data=data,weights=w)
这失败了,我得到了错误:
Error in model.frame.default(formula, data = data, weights = weights) :
invalid type (closure) for variable '(weights)'
同样,如果我打电话
my_modfunc(y ~ x1 + x2,data=data,weights='w')
我得到同样的错误。我怀疑环境,引用等存在一些问题。
剪切和粘贴lm的源代码,我可以将我的函数重写为
# based on lm
weird_modfunc <- function(formula,data,weights=NULL ) {
cl <- match.call() # what?
mf <- match.call(expand.dots = FALSE) # what??
m <- match(c("formula", "data", "weights"), names(mf), 0L)
mf <- mf[c(1L, m)] # ??
mf$drop.unused.levels <- TRUE # ??
mf[[1L]] <- quote(stats::model.frame) ## ???
mf <- eval(mf, parent.frame())
wt <- as.vector(model.weights(mf))
# do some fitting here...
}
# this runs without error:
weird_modfunc(y ~ x1 + x2,data=data,weights=w)
# this fails with the same error as above about variable lengths.
weird_modfunc(y ~ x1 + x2,data=data,weights='w')
问题在于这包含多个我不知道如何解释、修改或维护的有点神秘的咒语。
拨打model.frame 的正确方法是什么?使我的函数同时接受 weights=w 和 weights='w' 的奖励积分
【问题讨论】: