0

I have a linear regression which uses cities as groups in R:

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

I can make a vector of corresponding R-Squareds using this:

r_squareds <- summary(pop_model)$r.squared

But this does not give me the names of Cities. So, I don't know which R-Squared is for which regression. How can I make a table to record these R-Squareds together with their names into a dataframe to get a dataframe like this?:

City | R-Squared

Kaisar
  • 59
  • 5

1 Answers1

1

You can extract the city names from the names of residuals.

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

Example using mtcars dataset.

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
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Yes, thank you. Second part of your answer works. Calls on summary. However can we be sure that names from residuals are in the same order that names from R-Squared are? – Kaisar Aug 24 '21 at 04:36