通过R中的LM模型的变量列表创建循环 [英] Creating a loop through a list of variables for an LM model in R
问题描述
我正在尝试从变量组合列表中创建多个线性回归模型(如果更有用的话,我也将它们分别作为数据框使用!)
I am trying to create multiple linear regression models from a list of variable combinations (I also have them separately as a data-frame if that is more useful!)
变量列表如下:
Vars
x1+x2+x3
x1+x2+x4
x1+x2+x5
x1+x2+x6
x1+x2+x7
我正在使用的循环如下:
The loop I'm using looks like this:
for (i in 1:length(var_list)){
lm(independent_variable ~ var_list[i],data = training_data)
i+1
}
但是,它无法识别出将x1+x2+x3
等作为模型输入的var_list[i]
字符串.
However it is not recognizing the string of var_list[i]
which gives x1+x2+x3
etc. as a model input.
有人知道如何解决吗?
感谢您的帮助.
推荐答案
您甚至不必使用循环. Apply应该能很好地工作.
You don't even have to use loops. Apply should work nicely.
training_data <- as.data.frame(matrix(sample(1:64), nrow = 8))
colnames(training_data) <- c("independent_variable", paste0("x", 1:7))
Vars <- as.list(c("x1+x2+x3",
"x1+x2+x4",
"x1+x2+x5",
"x1+x2+x6",
"x1+x2+x7"))
allModelsList <- lapply(paste("independent_variable ~", Vars), as.formula)
allModelsResults <- lapply(allModelsList, function(x) lm(x, data = training_data))
如果需要模型摘要,可以添加:
If you need models summaries you can add :
allModelsSummaries = lapply(allModelsResults, summary)
例如,您可以通过执行以下操作来访问模型lm(independent_variable ~ x1+x2+x3)
的系数R²:
For example you can access the coefficient R² of the model lm(independent_variable ~ x1+x2+x3)
by doing this:
allModelsSummaries[[1]]$r.squared
希望对您有帮助.
这篇关于通过R中的LM模型的变量列表创建循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!