Extract R-square value with R in linear models [duplicate]

I know that using summary will help me to do this manually, however, I will have to calculted tons of R-squared values. Therefore, I need the computer to extract it for me. Here is a simple example:

library(alr3)
M.lm=lm(MaxSalary~Score,data=salarygov)
#Here you will see the R square value
summary(M.lm)

How can I do that?


Solution 1:

The R-squared, adjusted R-squared, and all other values you see in the summary are accessible from within the summary object. You can see everything by using str(summary(M.lm)):

> str(summary(M.lm))  # Truncated output...
List of 11
 $ call         : language lm(formula = MaxSalary ~ Score, data = salarygov)
 $ terms        :Classes 'terms', 'formula' length 3 MaxSalary ~ Score
 ...
 $ residuals    : Named num [1:495] -232.3 -132.6 37.9 114.3 232.3 ...
 $ coefficients : num [1:2, 1:4] 295.274 5.76 62.012 0.123 4.762 ...
 $ aliased      : Named logi [1:2] FALSE FALSE
 $ sigma        : num 507
 $ df           : int [1:3] 2 493 2
 $ r.squared    : num 0.817
 $ adj.r.squared: num 0.816
 $ fstatistic   : Named num [1:3] 2194 1 493
 $ cov.unscaled : num [1:2, 1:2] 1.50e-02 -2.76e-05 -2.76e-05 5.88e-08

To get the R-squared value, type summary(M.lm)$r.squared or summary(M.lm)$adj.r.squared

Solution 2:

With one predictor you could simply use cor(salarygov$MaxSalary ,salarygov$Score)^2. Alternatively, summary(M.lm)$r.squared.

Solution 3:

It depend which one you are interested in:

 # adjusted R²
 summary(M.lm)$adj.r.squared
 # R²
 summary(M.lm)$r.squared