Search code examples
rregressionlinear-regressioncoefficientscoefficient-of-determination

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


Solution

  • 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