r - 使用 `lm`参数在 `lapply`中调用 `weights`时出错

标签 r lapply lm

使用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/

相关文章:

r - 当因变量是因子/分类变量时的线性模型 (lm)?

r - 从 R 中的 lm 中提取变量以使用预测

r - 二进制矩阵的字符串列表

r - 从两个向量(名称、值)创建命名列表

r - 如何在 R 中替换 "unexpected escaped character"

R foreach并行找不到全局函数

r - 使用 `lapply` 对数据框 (R) 中的所有列进行 Winsorizing

r - 通过简单拟合预测 x 值并在图中注释

r - 在每个字符处拆分字符串

R函数找到与所有剩余向量相关性最高的向量