本文介绍了在带有`weights`参数的`lapply`中调用`lm`时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用weights参数在lapply中调用lm时遇到奇怪的行为.

I've encounter a weird behavior when calling lm within a lapply using the weights argument.

我的代码包含一个公式列表,在该公式上运行在lapply中调用的线性模型.到目前为止,一切正常:

My code consist of a list of formula on which I run a linear model that I call in lapply. So far it was working:

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参数时,出现一个奇怪的错误:

However, when I add the weights argument, I get a weird error:

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自变量.

It's like if the ... from lapply was conflicting with the ... of the lm call but only because of the weights argument.

任何想法都是造成此问题的原因,以及如何解决该问题?

Any idea was is the cause of this problem and how to fix it?

注意:使用不带lapply的呼叫将按预期工作:

NOTE: using the call without the lapply works as expected:

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中的lapply

EDIT The final call is a lapply within a function of the type:

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的注释:

lm在其开始行中两次使用match.call:

lm uses match.call twice in its opening lines:

cl <- match.call()
mf <- match.call(expand.dots = FALSE)

帮助文件中以及@Florian指出的解决方案是使用匿名函数包装器.

The solution noted in the help file and by @Florian is to use an anonymous function wrapper.

更新

对于更改模型公式的特定问题,您可以改写以避免通过使用updatelapply中调用lm:

For this specific problem of changing the model formula, you can rewrite to avoid calling lm within the lapply by using update instead:

# 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  

...

这篇关于在带有`weights`参数的`lapply`中调用`lm`时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 07:35