如何为R中的每一列运行lm回归 [英] how to run lm regression for every column in R
问题描述
我的数据框架为:
df=data.frame(x=rnorm(100),y1=rnorm(100),y2=rnorm(100),y3=...)
我想运行一个从第一列的第二列开始对每一列进行回归的循环:
I want to run a loop which regresses each column starting from the second column on the first column:
for(i in names(df[,-1])){
model = lm(i~x, data=df)
}
但是我失败了。关键是我想对每列进行回归循环,而某些列名称只是一个数字(例如404.1)。我找不到使用上述命令为每一列运行循环的方法。
But I failed. The point is that I want to do a loop of regression for each column and some column names is just a number (e.g. 404.1). I cannot find a way to run a loop for each column using the above command.
推荐答案
您的代码看起来不错,除非您调用 lm
中的 i
,R将读取 i
作为字符串,您无法将其退缩。使用 get
将允许您拉出与 i
相对应的列。
Your code looks fine except when you call i
within lm
, R will read i
as a string, which you can't regress things against. Using get
will allow you to pull the column corresponding to i
.
df=data.frame(x=rnorm(100),y1=rnorm(100),y2=rnorm(100),y3=rnorm(100))
storage <- list()
for(i in names(df)[-1]){
storage[[i]] <- lm(get(i) ~ x, df)
}
我创建一个空列表存储
,我将在循环的每次迭代中进行填充。这只是个人喜好,但我也建议您不要编写当前循环:
I create an empty list storage
, which I'm going to fill up with each iteration of the loop. It's just a personal preference but I'd also advise against how you've written your current loop:
for(i in names(df[,-1])){
model = lm(i~x, data=df)
}
您将覆盖模型
,因此仅返回最后的迭代结果。建议您将其更改为列表或可以迭代存储结果的矩阵。
You will overwrite model
, thus returning only the last iteration results. I suggest you change it to a list, or a matrix where you can iteratively store results.
希望有帮助
这篇关于如何为R中的每一列运行lm回归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!