ISYE 6414 — Regression Analysis| R Code Cheat Sheet Detailed.docx Georgia Institute Of Technology
ISYE 6414 — R Code Cheat Sheet
Regression Analysis · Modules 1–2 · SLR, ANOVA, MLR · Detailed with Library Sources
[library::pkg] Green tag = non-base R. Requires library() ⚠ Yellow row = common exam trap or gotcha
call.
1. Setup & Data
Task R Code [library]
Libraries — Load at Top of Every Script
data manipulation [dplyr] library(dplyr)
plotting [ggplot2] library(ggplot2)
dates [lubridate] library(lubridate)
rolling stats [zoo] library(zoo)
diagnostics & tests [car] library(car)
transformations [MASS] library(MASS)
CV helper [modelr] library(modelr)
functional programming [purrr] library(purrr)
ML CV [caret] library(caret)
Reading & Preprocessing
read CSV df <- read.csv('file.csv', header=TRUE)
set seed set.seed(100) # DO NOT CHANGE
convert to factor [base R] df$col <- as.factor(df$col)
convert date [base R] df$date <- as.Date(df$date, format='%m/%d/%Y')
check levels / baseline [base R] levels(df$col)
change baseline [base R] df$col <- relevel(df$col, ref='Clothing')
Train / Test Split
testRows <- sample(nrow(df), 0.2*nrow(df))
testData <- df[testRows, ]
80/20 split
trainData <- df[-testRows, ]
row.names(trainData) <- NULL
Feature Engineering
log transform df$log_x <- log(df$x) # or use log(Y) inline in lm()
interaction column df$ab <- df$a * df$b # or use a:b or a*b in formula
[dplyr] df <- df %>%
mutate(Age_Group = cut(Age,
bin numeric to groups breaks=c(0,18,25,35,45,55,65,75,85,100),
labels=c('0-18','19-25','26-35','36-45',
'46-55','56-65','66-75','76-85','86-100')))
2. Exploratory Data Analysis (EDA)
Task R Code [library]
Grouped Summaries
group mean + median [dplyr] df %>%
group_by(Category, Gender, Age_Group) %>%
, summarise(
avg = mean(Amount, na.rm=TRUE),
med = median(Amount, na.rm=TRUE)
)
[dplyr] df %>%
group_by(col) %>%
highest group by total
summarise(total = sum(Amount, na.rm=TRUE)) %>%
filter(total == max(total))
[dplyr] df %>%
filter(Category == "Electronics") %>%
most frequent location
count(Store_Location) %>%
filter(n == max(n))
Time Series
[lubridate] df <- df %>%
add month column mutate(Month = floor_date(Date, unit="month"))
[dplyr] monthly <- df %>%
group_by(Month, Category) %>%
monthly avg by group
summarise(Avg = mean(Amount, na.rm=TRUE)) %>%
ungroup()
[zoo] monthly <- monthly %>%
group_by(Category) %>%
3-month rolling mean (center) mutate(Rolling = rollapply(Avg, width=3,
FUN=mean, align='center', fill=NA)) %>%
ungroup()
Correlation
[base R] cor(df$X, df$Y)
correlation coefficient
# │r│ < 0.4 weak · 0.4–0.7 moderate · ≥0.7 strong
correlation matrix [base R] cor(df[, c('X1','X2','X3')])
Plots
[base R] plot(df$X, df$Y, xlab='X', ylab='Y', col='blue')
scatter + regression line
abline(lm(Y~X, data=df), col='red')
[ggplot2] ggplot(df, aes(x=Category, y=Score, color=Category)) +
geom_boxplot() +
boxplot (ggplot)
theme(axis.text.x=element_text(angle=45, hjust=1)) +
ggtitle("Title")
[ggplot2] ggplot(monthly, aes(x=Month, y=Avg, color=Category)) +
geom_line() +
line plot (time series)
scale_x_date(date_labels="%b %Y", date_breaks="1 month") +
theme(axis.text.x=element_text(angle=45, hjust=1))
3. Simple Linear Regression (SLR)
Task R Code [library]
Fitting & Summary
[base R] model1 <- lm(Y ~ X, data=trainData)
fit SLR
summary(model1)
[base R] coef(model1)
extract coefficients
coef(model1)['X']
[base R] (summary(model1)$sigma)^2
MSE (sigma-hat²) # sigma = residual std error → MSE = sigma²
R² [base R] summary(model1)$r.squared
Adjusted R² [base R] summary(model1)$adj.r.squared
Inference
95% CI for coefficients [base R] confint(model1, level=0.95)
ISYE 6414 — R Code Cheat Sheet
Regression Analysis · Modules 1–2 · SLR, ANOVA, MLR · Detailed with Library Sources
[library::pkg] Green tag = non-base R. Requires library() ⚠ Yellow row = common exam trap or gotcha
call.
1. Setup & Data
Task R Code [library]
Libraries — Load at Top of Every Script
data manipulation [dplyr] library(dplyr)
plotting [ggplot2] library(ggplot2)
dates [lubridate] library(lubridate)
rolling stats [zoo] library(zoo)
diagnostics & tests [car] library(car)
transformations [MASS] library(MASS)
CV helper [modelr] library(modelr)
functional programming [purrr] library(purrr)
ML CV [caret] library(caret)
Reading & Preprocessing
read CSV df <- read.csv('file.csv', header=TRUE)
set seed set.seed(100) # DO NOT CHANGE
convert to factor [base R] df$col <- as.factor(df$col)
convert date [base R] df$date <- as.Date(df$date, format='%m/%d/%Y')
check levels / baseline [base R] levels(df$col)
change baseline [base R] df$col <- relevel(df$col, ref='Clothing')
Train / Test Split
testRows <- sample(nrow(df), 0.2*nrow(df))
testData <- df[testRows, ]
80/20 split
trainData <- df[-testRows, ]
row.names(trainData) <- NULL
Feature Engineering
log transform df$log_x <- log(df$x) # or use log(Y) inline in lm()
interaction column df$ab <- df$a * df$b # or use a:b or a*b in formula
[dplyr] df <- df %>%
mutate(Age_Group = cut(Age,
bin numeric to groups breaks=c(0,18,25,35,45,55,65,75,85,100),
labels=c('0-18','19-25','26-35','36-45',
'46-55','56-65','66-75','76-85','86-100')))
2. Exploratory Data Analysis (EDA)
Task R Code [library]
Grouped Summaries
group mean + median [dplyr] df %>%
group_by(Category, Gender, Age_Group) %>%
, summarise(
avg = mean(Amount, na.rm=TRUE),
med = median(Amount, na.rm=TRUE)
)
[dplyr] df %>%
group_by(col) %>%
highest group by total
summarise(total = sum(Amount, na.rm=TRUE)) %>%
filter(total == max(total))
[dplyr] df %>%
filter(Category == "Electronics") %>%
most frequent location
count(Store_Location) %>%
filter(n == max(n))
Time Series
[lubridate] df <- df %>%
add month column mutate(Month = floor_date(Date, unit="month"))
[dplyr] monthly <- df %>%
group_by(Month, Category) %>%
monthly avg by group
summarise(Avg = mean(Amount, na.rm=TRUE)) %>%
ungroup()
[zoo] monthly <- monthly %>%
group_by(Category) %>%
3-month rolling mean (center) mutate(Rolling = rollapply(Avg, width=3,
FUN=mean, align='center', fill=NA)) %>%
ungroup()
Correlation
[base R] cor(df$X, df$Y)
correlation coefficient
# │r│ < 0.4 weak · 0.4–0.7 moderate · ≥0.7 strong
correlation matrix [base R] cor(df[, c('X1','X2','X3')])
Plots
[base R] plot(df$X, df$Y, xlab='X', ylab='Y', col='blue')
scatter + regression line
abline(lm(Y~X, data=df), col='red')
[ggplot2] ggplot(df, aes(x=Category, y=Score, color=Category)) +
geom_boxplot() +
boxplot (ggplot)
theme(axis.text.x=element_text(angle=45, hjust=1)) +
ggtitle("Title")
[ggplot2] ggplot(monthly, aes(x=Month, y=Avg, color=Category)) +
geom_line() +
line plot (time series)
scale_x_date(date_labels="%b %Y", date_breaks="1 month") +
theme(axis.text.x=element_text(angle=45, hjust=1))
3. Simple Linear Regression (SLR)
Task R Code [library]
Fitting & Summary
[base R] model1 <- lm(Y ~ X, data=trainData)
fit SLR
summary(model1)
[base R] coef(model1)
extract coefficients
coef(model1)['X']
[base R] (summary(model1)$sigma)^2
MSE (sigma-hat²) # sigma = residual std error → MSE = sigma²
R² [base R] summary(model1)$r.squared
Adjusted R² [base R] summary(model1)$adj.r.squared
Inference
95% CI for coefficients [base R] confint(model1, level=0.95)