-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathRegression.R
82 lines (57 loc) · 2.15 KB
/
Regression.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File: Regression.R
# Course: R: An Introduction (with RStudio)
# INSTALL AND LOAD PACKAGES ################################
library(datasets) # Load base packages manually
# Installs pacman ("package manager") if needed
if (!require("pacman")) install.packages("pacman")
# Use pacman to load add-on packages as desired
pacman::p_load(pacman, caret, lars, tidyverse)
# LOAD DATA ################################################
?USJudgeRatings
head(USJudgeRatings)
data <- USJudgeRatings
# Define variable groups
x <- as.matrix(data[, -12])
y <- data[, 12]
# REGRESSION WITH SIMULTANEOUS ENTRY #######################
# Using variable groups
reg1 <- lm(y ~ x)
# Or specify variables individually
reg1 <- lm(RTEN ~ CONT + INTG + DMNR + DILG + CFMG +
DECI + PREP + FAMI + ORAL + WRIT + PHYS,
data = USJudgeRatings)
# Results
reg1 # Coefficients only
summary(reg1) # Inferential tests
# MORE SUMMARIES ###########################################
anova(reg1) # Coefficients w/inferential tests
coef(reg1) # Coefficients (same as reg1)
confint(reg1) # CI for coefficients
resid(reg1) # Residuals case-by-case
hist(residuals(reg1)) # Histogram of residuals
# ADDITIONAL MODELS ########################################
# Conventional stepwise regression
stepwise <- lars(x, y, type = "stepwise")
# Stagewise: Like stepwise but with better generalizability
forward <- lars(x, y, type = "forward.stagewise")
# LAR: Least Angle Regression
lar <- lars(x, y, type = "lar")
# LASSO: Least Absolute Shrinkage and Selection Operator
lasso <- lars(x, y, type = "lasso")
# Comparison of R^2 for new models
r2comp <- c(stepwise$R2[6], forward$R2[6],
lar$R2[6], lasso$R2[6]) %>%
round(2)
names(r2comp) <- c("stepwise", "forward", "lar", "lasso")
r2comp # Show values of R^2
# CLEAN UP #################################################
# Clear environment
rm(list = ls())
# Clear packages
p_unload(all) # Remove all add-ons
detach("package:datasets", unload = TRUE) # For base
# Clear plots
dev.off() # But only if there IS a plot
# Clear console
cat("\014") # ctrl+L
# Clear mind :)