Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

lm

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?

like image 561
Zander Avatar asked May 07 '14 13:05

Zander


People also ask

How do you find the R-squared of a linear model in R?

Solution. To calculate R2 you need to find the sum of the residuals squared and the total sum of squares. Start off by finding the residuals, which is the distance from regression line to each data point. Work out the predicted y value by plugging in the corresponding x value into the regression line equation.

Can you get R2 from R?

R square value using summary() function. We can even make use of the summary() function in R to extract the R square value after modelling. In the below example, we have applied the linear regression model on our data frame and then used summary()$r. squared to get the r square value.

What is R2 in linear regression?

R-Squared (R² or the coefficient of determination) is a statistical measure in a regression model that determines the proportion of variance in the dependent variable that can be explained by the independent variable. In other words, r-squared shows how well the data fit the regression model (the goodness of fit).


Video Answer


2 Answers

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

like image 194
Andrew Avatar answered Oct 21 '22 05:10

Andrew


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

like image 22
Roland Avatar answered Oct 21 '22 04:10

Roland