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

问题描述 投票:3回答:3

我知道某个地方会存在这样的问题,但我找不到它。我有变量a, b, c, d,我想写一个循环,这样我回归并附加变量并再次使用附加变量回归

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

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

你会怎么做?

编辑

这是下一个相关的问题:Link

r regression lm
3个回答
2
投票
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]])(第二个)检查单个结果。


3
投票

使用paste和as.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)
})

注意:看起来像一个重复的帖子,我已经看到了这类问题的更好的解决方案,此刻找不到。


3
投票

你可以用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
© www.soinside.com 2019 - 2024. All rights reserved.