首页 > 解决方案 > 如何将线性回归的 R 平方与组名一起记录到 R 中的数据框中?

问题描述

我有一个线性回归,它使用城市作为 R 中的组:

pop_model <- lmList(Value ~ Year | City, data = df)

我可以使用以下方法制作相应 R-Squareds 的向量:

r_squareds <- summary(pop_model)$r.squared

但这并没有给我城市的名称。所以,我不知道哪个 R-Squared 是针对哪个回归的。如何制作表格以将这些 R-Squareds 及其名称一起记录到数据框中以获得这样的数据框?:

城市 | R平方

标签: rregressionlinear-regressioncoefficientscoefficient-of-determination

解决方案


names您可以从of中提取城市名称residuals

data <- data.frame(city = names(pop_model$residuals),
                   R_squared = pop_model$r.squared)

使用数据集的示例mtcars

library(nlme)

pop_model <- lmList(mpg ~ am | cyl, data = mtcars)

tmp <- summary(pop_model)

data <- data.frame(cyl = names(tmp$residuals), 
                   R_squared = tmp$r.squared)

data

#  cyl   R_squared
#1   4 0.287289249
#2   6 0.281055142
#3   8 0.002464789

推荐阅读