62

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?

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
Zander
  • 988
  • 1
  • 9
  • 16

3 Answers3

106

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

Andrew
  • 36,541
  • 13
  • 67
  • 93
  • This only seems to work when there is one left hand side variable. – John Apr 28 '15 at 20:58
  • 2
    The summary variables should still all appear when there are two lefthand side variables, though. See `str(summary(lm(price + carat ~ x + y + z, data=ggplot2::diamonds)))` – Andrew May 01 '15 at 21:46
12

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

Roland
  • 127,288
  • 10
  • 191
  • 288
12

It depend which one you are interested in:

 # adjusted R²
 summary(M.lm)$adj.r.squared
 # R²
 summary(M.lm)$r.squared
droopy
  • 2,788
  • 1
  • 14
  • 12