Adam G
Adam G

Reputation: 125

Extracting a list of R2 from within lm() based on variable in multiple regression in R

I've performed a multiple regression analysis on a dataset in R using lm() and I am able to extract the coefficients for each day of year using the function below. I would also like to extract the R2 for each day of year but this doesn't seem to work in the same way.

This is pretty much the same question as: Print R-squared for all of the models fit with lmList but when I try this I get 'Error: $ operator is invalid for atomic vectors'. I would also like to include it in the same function if possible. How can I extract the R2 for each doy in this way?

#Create MR function for extracting coefficients
getCoef <- function(df) {
  coefs <- lm(y ~ T + P + L + T * L + P * L, data = df)$coef
  names(coefs) <- c("intercept", "T", "P", "L", "T_L", "P_L")
  coefs
}

#Extract coefficients for each doy
coefs.MR_uM <- ddply(MR_uM, ~ doy, getCoef)```

Upvotes: 1

Views: 1619

Answers (1)

nghauran
nghauran

Reputation: 6768

The point is r.squared is stored in summary(lm(...)) not in lm(...). Here is another version of your function to extract R2:

library(plyr)
df <- iris
#Create MR function for extracting coefficients and R2
getCoef <- function(df) {
        model <- lm(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width, data = df)
        coefs <- model$coef
        names(coefs) <- c("intercept", "Sepal.Width", "Petal.Length", "Petal.Width")
        R2 <- summary(model)$r.squared
        names(R2) <- c("R2")
        c(coefs, R2)
}
#Extract coefficients and R2 for each Species
coefs.MR_uM <- ddply(df, ~ Species, getCoef)
coefs.MR_uM # output
     Species intercept Sepal.Width Petal.Length Petal.Width        R2
1     setosa  2.351890   0.6548350    0.2375602   0.2521257 0.5751375
2 versicolor  1.895540   0.3868576    0.9083370  -0.6792238 0.6050314
3  virginica  0.699883   0.3303370    0.9455356  -0.1697527 0.7652193

As suggested by Parfait, you don't need plyr::ddply(), you can use do.call(rbind, by(df, df$Species, getCoef))

Hope this helps !

Upvotes: 4

Related Questions