众多多元回归,每次更改一个变量

时间:2019-01-08 14:39:55

标签: r

我有用于运行多元回归的基本R代码:

fit <-lm(coldbreed + gender + 237,data = rweights

但是,我想多次运行此代码,每次都稍作调整。上面写着“ 237”(列标题),可以是1-1000之间的任何数字(也是列标题),我想对每一列运行多元回归。所以我希望它运行的等效项:

fit <-lm(var1var2 + var3 + 1,data = rweights

fit <-lm(var1var2 + var3 + 2,data = rweights

....

fit <-lm(var1var2 + var3 + 1000,data = rweights

然后,我打算分析这些多个多元回归的结果,因此理想情况下将有一个很好的输出来对所有这些结果进行整理,但是我很欣赏那可能是另一个问题!任何建议将不胜感激。

1 个答案:

答案 0 :(得分:1)

下面是一些示例代码,可以帮助您入门:

### Generate fake data
n = 1000
var1 = rnorm(n)
var2 = rnorm(n)
var3 = rnorm(n)
k = 10
dat = data.frame(var1, var2, var3, matrix(runif(n*k), n, k))

### Object where all the fitted models are stored
mods = rep(list(NULL), k)

### Loop through the different models
for (i in 1:k){
    form = paste0("var1 ~ var2 + var3 + X", i)
    mods[[i]] = lm(as.formula(form), data = dat)
    }

### Examples
summary(mods[[1]])
summary(mods[[2]])

如汤姆·哈多(Tom Haddow)在评论中所建议,可以将其概括的一种方法是使用colnames

mods = rep(list(NULL), k)

# Get column names, remove the ones you don't want to loop through
varlist = colnames(dat)[-(1:3)]

for (i in 1:k){
    form = paste0("var1 ~ var2 + var3 + ", varlist[i])
    mods[[i]] = lm(as.formula(form), data = dat)
    }
summary(mod[[1]])

甚至

mods = rep(list(NULL), k)
varlist = colnames(dat)[-(1:3)]

for (v in varlist){
    form = paste0("var1 ~ var2 + var3 + ", v)
    mods[[v]] = lm(as.formula(form), data = dat)
    }
summary(mods$X1)

唯一的区别在于您如何访问mods中的元素。