Skip to content

Instantly share code, notes, and snippets.

@aravindhebbali
Last active March 8, 2022 06:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aravindhebbali/fb8c7d496722919c57ba89a58c65602c to your computer and use it in GitHub Desktop.
Save aravindhebbali/fb8c7d496722919c57ba89a58c65602c to your computer and use it in GitHub Desktop.
Sort best subset selection by AIC
# load packages
library(olsrr)
#> 
#> Attaching package: 'olsrr'
#> The following object is masked from 'package:datasets':
#> 
#>     rivers

# regression
model <- lm(mpg ~ disp + hp + wt + qsec, data = mtcars)

# store output 
k <- ols_step_best_subset(model)

# access metrics
result <- k$metrics

# sort by aic
# base R
result[order(result$aic), ]
#>   mindex n      predictors   rsquare      adjr   predrsq        cp      aic
#> 2      2 2           hp wt 0.8267855 0.8148396 0.7810871  2.369005 156.6523
#> 3      3 3      hp wt qsec 0.8347678 0.8170643 0.7819955  3.061665 157.1426
#> 4      4 4 disp hp wt qsec 0.8351443 0.8107212 0.7710297  5.000000 159.0696
#> 1      1 1              wt 0.7528328 0.7445939 0.7086954 12.480939 166.0294
#>       sbic      sbc     msep      fpe       apc       hsp
#> 2 66.57546 162.5153 215.5104 7.356327 0.2090520 0.2402066
#> 3 67.72382 164.4713 213.1929 7.475597 0.2124414 0.2461102
#> 4 70.04081 167.8640 220.8882 7.949661 0.2259134 0.2644378
#> 1 74.29156 170.4266 296.9167 9.857235 0.2801228 0.3199103

# dplyr
dplyr::arrange(result, aic)
#>   mindex n      predictors   rsquare      adjr   predrsq        cp      aic
#> 2      2 2           hp wt 0.8267855 0.8148396 0.7810871  2.369005 156.6523
#> 3      3 3      hp wt qsec 0.8347678 0.8170643 0.7819955  3.061665 157.1426
#> 4      4 4 disp hp wt qsec 0.8351443 0.8107212 0.7710297  5.000000 159.0696
#> 1      1 1              wt 0.7528328 0.7445939 0.7086954 12.480939 166.0294
#>       sbic      sbc     msep      fpe       apc       hsp
#> 2 66.57546 162.5153 215.5104 7.356327 0.2090520 0.2402066
#> 3 67.72382 164.4713 213.1929 7.475597 0.2124414 0.2461102
#> 4 70.04081 167.8640 220.8882 7.949661 0.2259134 0.2644378
#> 1 74.29156 170.4266 296.9167 9.857235 0.2801228 0.3199103

Created on 2022-03-08 by the reprex package (v0.3.0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment