Kaisar
Kaisar

Reputation: 59

How to record R Squareds of a linear regression together with the group name into a data frame in R?

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

Upvotes: 0

Views: 56

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388797

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

Upvotes: 1

Related Questions