在具有 ifelse 条件的 lapply 中使用 lm()

Using lm() within lapply with ifelse condition

我正在尝试 运行 使用 lapply 进行多次回归。我想使用 ifelse 条件来区分哪个回归到 运行。但是,当我使用 ifelse 时,输出不是 lm 对象。我附上了重现我的问题的代码。请帮忙。

attach(iris)

names.list = c('a','b','c')

models.work = lapply(names.list,
                    function(f)
                      {
                      lm(Sepal.Length~Sepal.Width,data=iris)
                     })

models.not.work = lapply(names.list,
                     function(f)
                     {
                      ifelse(1==1,
                      lm(Sepal.Length~Sepal.Width,data=iris),
                      lm(Sepal.Length~Sepal.Width,data=iris)
                      )
                     })
在这种情况下,

ifelse 不能 return 模型对象。使用正常的 if-else 子句,就可以了。

attach(iris)

names.list = c('a','b','c')
models.not.work = lapply(names.list,
                         function(f)
                         {
                           if(1==1){
                                  lm(Sepal.Length~Sepal.Width,data=iris)}else{
                                  lm(Sepal.Length~Sepal.Width,data=iris)
                                  }

                         })


#output

> models.not.work[[1]]

Call:
lm(formula = Sepal.Length ~ Sepal.Width, data = iris)

Coefficients:
(Intercept)  Sepal.Width  
     6.5262      -0.2234  

ifelse 说 returns:

A vector of the same length and attributes (including dimensions and "class") as test

其中 test 是输入。您的输入是 1==1(顺便说一句,您可以只使用 TRUE),输入长度为 1。因此 ifelse 将 return 长度为 1 的内容。lm return 是一个列表,因此它只会 return 该列表中的第一个元素。这恰好是系数。

ifelse 不是您想在这里使用的。目前尚不清楚您实际想要做什么,但很可能有更好的方法来实现您的实际目标。

如果您无论如何都要手动循环元素,您可能只想使用普通的 if 语句。不过,如果您解释一下您实际尝试做的事情,可能会有更好的方法。