[英]How to only print (adjusted) R-squared of regression model?
I am a beginner with R. I have a data set on air pollution.我是 R 的初学者。我有一个关于空气污染的数据集。 The columns are site, measured concentration and 80 variables (v1-v80) that might influence the concentration.列是站点、测量浓度和可能影响浓度的 80 个变量 (v1-v80)。 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()).我想用我自己的代码制作一个基于 R-squared/adj 的正向逐步回归模型(所以我不想使用像 step() 或 regsubset() 这样的东西)。 The dependent variable is concentration and the variables v1-v80 as independent variables.因变量是浓度,变量 v1-v80 作为自变量。 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))
}
This works well, but I am only interested in R-squared and adjusted R-squared.这很有效,但我只对 R 平方和调整后的 R 平方感兴趣。 I tried to only have (adjusted) R-squared printed with:我尝试只打印(调整后的)R 平方:
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.等等。
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?对于在 for 循环中生成的每个模型,如何仅获得相关变量的名称和(调整后的)R 平方作为输出?
Thanks!谢谢!
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
Using base R使用基础 R
summary(model)$adj.r.squared
summary(model)$r.squared
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.