使用lm
参数在lapply
中调用weights
时遇到奇怪的行为。
我的代码包含一个公式列表,在该公式上运行一个我称为lapply
的线性模型。到目前为止,它正在工作:
dd <- data.frame(y = rnorm(100),
x1 = rnorm(100),
x2 = rnorm(100),
x3 = rnorm(100),
x4 = rnorm(100),
wg = runif(100,1,100))
ls.form <- list(
formula(y~x1+x2),
formula(y~x3+x4),
formula(y~x1|x2|x3),
formula(y~x1+x2+x3+x4)
)
res.no.wg <- lapply(ls.form, lm, data = dd)
但是,当我添加
weights
参数时,出现一个奇怪的错误:res.with.wg <- lapply(ls.form, lm, data = dd, weights = dd[,"wg"])
Error in eval(extras, data, env) :
..2 used in an incorrect context, no ... to look in
这就好像
...
中的lapply
与...
调用的lm
冲突,但仅是因为weights
参数所致。任何想法都是造成此问题的原因,以及如何解决该问题?
注意:使用不带
lapply
的调用可以按预期工作:lm(ls.form[[1]], data = dd, weights = dd[,"wg"] )
Call:
lm(formula = ls.form[[1]], data = dd, weights = dd[, "wg"])
Coefficients:
(Intercept) x1 x2
-0.12020 0.06049 -0.01937
编辑最后的调用是以下类型的
lapply
中的function
:f1 <- function(samp, dat, wgt){
res.with.wg2 <- lapply(ls.form, function(x) {lm(formula = x, data=dat[samp,], weights=dat[samp,wgt])})
}
f1(1:66, dat=dd, wgt = "wg")
最佳答案
帮助文件中有lapply
的注释:
For historical reasons, the calls created by lapply are unevaluated, and code has been written (e.g., bquote) that relies on this. This means that the recorded call is always of the form FUN(X[[i]], ...), with i replaced by the current (integer or double) index. This is not normally a problem, but it can be if FUN uses sys.call or match.call or if it is a primitive function that makes use of the call. This means that it is often safer to call primitive functions with a wrapper, so that e.g. lapply(ll, function(x) is.numeric(x)) is required to ensure that method dispatch for is.numeric occurs correctly.
lm
在其开头的行中两次使用了match.call
:cl <- match.call()
mf <- match.call(expand.dots = FALSE)
帮助文件中和@Florian指出的解决方案是使用匿名函数包装器。
更新
对于更改模型公式的特定问题,您可以重写以免通过使用
lm
来调用lapply
中的update
:# create base model (the formula here doesn't really matter, but we can specify the weights safely here)
baselm <- lm(y+x1,data=dd,weights=dd[,"wg"])
# update with lapply
lapply(ls.form,update,object=baselm)
[[1]]
Call:
lm(formula = y ~ x1 + x2, data = dd, weights = dd[, "wg"])
Coefficients:
(Intercept) x1 x2
0.07561 0.16111 0.15014
...
关于r - 使用 `lm`参数在 `lapply`中调用 `weights`时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47907626/