0

I was trying to calculate the predicted R square in R programming language for a multiple linear regression model, like one we get in Minitab.

go through this link it gives how it's done in Minitab. But I am not aware how it's done in R

https://statisticsbyjim.com/regression/interpret-adjusted-r-squared-predicted-r-squared-regression/

2 Answers2

2

Please check: predicted R squared computation

#PRESS - predicted residual sums of squares

PRESS <- function(linear.model) {
  #' calculate the predictive residuals
  pr <- residuals(linear.model)/(1-lm.influence(linear.model)$hat)
  #' calculate the PRESS
  PRESS <- sum(pr^2)
  
  return(PRESS)
}

pred_r_squared <- function(linear.model) {
  #' Use anova() to get the sum of squares for the linear model
  lm.anova <- anova(linear.model)
  #' Calculate the total sum of squares
  tss <- sum(lm.anova$'Sum Sq')
  # Calculate the predictive R^2
  pred.r.squared <- 1-PRESS(linear.model)/(tss)
  
  return(pred.r.squared)
}

I tested on a random model:

model <- lm(disp ~ mpg, mtcars)    
pred_r_squared(model)
#0.6815513
AlexB
  • 3,061
  • 2
  • 17
  • 19
0

The linear model has a summary function, which can be used as follows:

set.seed(0)
y <- 1:10
x <- runif(10)
summary(lm(y~x))

#Call:
#lm(formula = y ~ x)

#Residuals:
#    Min      1Q  Median      3Q     Max 
#-5.1468 -1.7243 -0.1631  1.6937  4.5146 

#Coefficients:
#            Estimate Std. Error t value Pr(>|t|)
#(Intercept)    3.931      2.561   1.535    0.163
#x              2.472      3.720   0.664    0.525

#Residual standard error: 3.126 on 8 degrees of freedom
#Multiple R-squared:  0.0523,   Adjusted R-squared:  -0.06616 
#F-statistic: 0.4415 on 1 and 8 DF,  p-value: 0.5251

You can specifically get the R-squared or adjusted R-squared with:

summary(lm(y~x))$r.squared

or

summary(lm(y~x))$adj.r.squared
Miff
  • 7,486
  • 20
  • 20