Building a matrix from model summary

Without a reprex. See the FAQ, I can only offer an approach

model <- function(x) {
  result = summary(lm(mpg ~ mtcars[x][[1]], mtcars))
  return(c(result$r.squared,result$adj.r.squared,
         result$adj.r.squared-result$r.squared))
}

# source object is mtcars
# target object is a matrix to show the 
# r squared, adjusted r squared and their difference

# empty matrix for up to 10 variables to be used
# as regressors on mpg in mtcars

m <- matrix(nrow = 11, ncol = 3)

# populate the matrix row-wise
for(i in 1:11) m[i,] = model(i)
#> Warning in summary.lm(lm(mpg ~ mtcars[x][[1]], mtcars)): essentially perfect
#> fit: summary may be unreliable
# first row is mpg ~ mpg
m
#>            [,1]      [,2]         [,3]
#>  [1,] 1.0000000 1.0000000  0.000000000
#>  [2,] 0.7261800 0.7170527 -0.009127333
#>  [3,] 0.7183433 0.7089548 -0.009388555
#>  [4,] 0.6024373 0.5891853 -0.013252089
#>  [5,] 0.4639952 0.4461283 -0.017866828
#>  [6,] 0.7528328 0.7445939 -0.008238907
#>  [7,] 0.1752963 0.1478062 -0.027490123
#>  [8,] 0.4409477 0.4223126 -0.018635077
#>  [9,] 0.3597989 0.3384589 -0.021340035
#> [10,] 0.2306734 0.2050292 -0.025644218
#> [11,] 0.3035184 0.2803024 -0.023216052
# discard first row
m[-1, ]
#>            [,1]      [,2]         [,3]
#>  [1,] 0.7261800 0.7170527 -0.009127333
#>  [2,] 0.7183433 0.7089548 -0.009388555
#>  [3,] 0.6024373 0.5891853 -0.013252089
#>  [4,] 0.4639952 0.4461283 -0.017866828
#>  [5,] 0.7528328 0.7445939 -0.008238907
#>  [6,] 0.1752963 0.1478062 -0.027490123
#>  [7,] 0.4409477 0.4223126 -0.018635077
#>  [8,] 0.3597989 0.3384589 -0.021340035
#>  [9,] 0.2306734 0.2050292 -0.025644218
#> [10,] 0.3035184 0.2803024 -0.023216052

Created on 2023-03-24 with reprex v2.0.2

1 Like