迭代列表并附加以在 R 中进行回归

Iterate over list and append in order to do a regression in R

我知道某个地方会有这样的问题,但是我没找到。我有变量 a, b, c, d 并且我想编写一个循环,以便我回归并附加变量并再次回归附加变量

lm(Y ~ a, data = data), 那么 lm(Y ~ a + b, data = data),然后

lm(Y ~ a + b + c, data = data)

你会怎么做?

vars = c('a', 'b', 'c', 'd')
# might want to use a subset of names(data) instead of
# manually typing the names

reg_list = list()
for (i in seq_along(vars)) {
  my_formula = as.formula(sprintf('Y ~ %s', paste(vars[1:i], collapse = " + ")))
  reg_list[[i]] = lm(my_formula, data = data)
}

然后您可以检查单个结果,例如 summary(reg_list[[2]])(对于第二个结果)。

使用pasteas.formula,示例使用mtcars 数据集:

myFits <- lapply(2:ncol(mtcars), function(i){
  x <- as.formula(paste("mpg", 
                        paste(colnames(mtcars)[2:i], collapse = "+"), 
                        sep = "~"))
  lm(formula = x, data = mtcars)
})

注意:看起来像重复的post,我已经看到了针对此类问题的更好解决方案,目前找不到。

您可以使用 lapply / reformulate 方法来做到这一点。

formulae <- lapply(ivars, function(x) reformulate(x, response="Y"))
lapply(formulae, function(x) summary(do.call("lm", list(x, quote(dat)))))

数据

set.seed(42)
dat <- data.frame(matrix(rnorm(80), 20, 4, dimnames=list(NULL, c("Y", letters[1:3]))))
ivars <- sapply(1:3, function(x) letters[1:x])  # create an example vector ov indep. variables