问题描述
我是R的初学者.我有一个有关空气污染的数据集.列是站点,测量浓度和可能影响浓度的80个变量(v1-v80).我想用自己的代码基于R-平方/adj建立具有逐步逐步回归的模型(因此,我不想使用诸如step()或regsubset()之类的东西).因变量是浓度,变量v1-v80是自变量.我为第一步编写了以下代码(简化了数据集):
I am a beginner with R. I have a data set on air pollution. The columns are site, measured concentration and 80 variables (v1-v80) that might influence the concentration.I want to make a model with forward stepwise regression based on R-squared/adj with my own code (so I do not want to use something like step() or regsubset()). The dependent variable is concentration and the variables v1-v80 as independent variables. I wrote the following code for the first step (data set is simplified):
site concentration v1 v2 v3
1 1 -0.84085548 1.7114409 -0.2857736 -1.0803926
2 2 1.38435934 -0.6029080 0.1381082 -0.1575344
3 3 -1.25549186 -0.4721664 1.2276303 -1.0717600
for (j in names(df)){
model <- lm(concentration ~ df[[j]], data = df)
print(j)
print(summary(model))
}
这很好用,但是我只对R平方和调整后的R平方感兴趣.我尝试只用(调整后的)R平方打印:
This works well, but I am only interested in R-squared and adjusted R-squared. I tried to only have (adjusted) R-squared printed with:
for (j in names(df)){
model <- lm(concentration ~ df[[j]], data = df)
print(j)
print(summary(model$r.squared))
print(summary(model$adj.r.squared))
}
但是随后我得到了输出(这只是一部分):
But then I get as output (this is only a part):
[1] "v1"
Length Class Mode
0 NULL NULL
Length Class Mode
0 NULL NULL
[1] "v2"
Length Class Mode
0 NULL NULL
Length Class Mode
0 NULL NULL
Etcetera.
对于在for循环中生成的每个模型,我如何只获取相关变量的名称和(调整后的)R平方作为输出?
How can I get as output only the name of the relevant variable and (adjusted) R-squared for every model that is produced in the for-loop?
谢谢!
推荐答案
library(broom)
glance(model)[c(1,2)]
Input = ("site concentration v1 v2 v3
1 1 -0.84085548 1.7114409 -0.2857736 -1.0803926
2 2 1.38435934 -0.6029080 0.1381082 -0.1575344
3 3 -1.25549186 -0.4721664 1.2276303 -1.0717600")
df = read.table(textConnection(Input),header=TRUE)
for (j in names(df)){
model <- lm(concentration ~ df[[j]], data = df)
print(j)
print(glance(model)[c(1,2)])
}
[1] "site"
r.squared adj.r.squared
1 0.02132635 -0.9573473
[1] "concentration"
r.squared adj.r.squared
1 1 1
[1] "v1"
r.squared adj.r.squared
1 0.1717716 -0.6564568
[1] "v2"
r.squared adj.r.squared
1 0.1482473 -0.7035055
[1] "v3"
r.squared adj.r.squared
1 0.9762587 0.9525174
Warning message:
In stats::summary.lm(x) :
essentially perfect fit: summary may be unreliable
使用基数R
summary(model)$adj.r.squared
summary(model)$r.squared
这篇关于如何仅打印(调整后的)回归模型的R平方?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!