#
THE MASTER R SCRIPT: DA 3003 – DATA PREPROCESSING & VISUALIZATION
Complete Reference Guide for:
1. Setup & Import
2. Data Inspection
3. Data Integration (Joins & Stacking)
4. Missing Value Handling
5. Outlier Detection & Treatment
6. Data Transformations
7. Basic & Intermediate ggplot2 Visualizations
8. Advanced Visualizations (Maps, Heatmaps, Correlograms, Mosaic)
9. Saving Outputs
#
==============================================================================
1. SETUP & IMPORT
==============================================================================
Install packages if you haven’t already:
install.packages(c(“ggplot2”, “dplyr”, “scales”, “maps”, “corrplot”, “tidyr”, “leaflet”))
Load necessary libraries
library(ggplot2) # For core plotting and visualization
library(dplyr) # For data manipulation and piping (%>%)
library(scales) # For axis formatting (e.g., percentages)
library(maps) # For static map data
library(corrplot) # For correlation matrix plots
library(tidyr) # For pivoting data (wide to long)
library(leaflet) # For interactive maps
Set working directory (Update this path to your local folder)
setwd(“C:/Your/Path/Here”)
Read datasets (na.strings ensures blank spaces are treated as missing values)
df <- read.csv(“your_data.csv”, na.strings = c(“”, “NA”))
==============================================================================
2. DATA INSPECTION
==============================================================================
Basic structural checks
head(df) # First 6 rows
head(df, 10) # First 10 rows
tail(df) # Last 6 rows
dim(df) # Dimensions (Row count, Column count)
nrow(df) # Number of rows
ncol(df) # Number of columns
str(df) # Structure and variable types
summary(df) # Descriptive statistics for each column
names(df) # Vector of column names
col_names <- names(df)# Assign column names to a variable
==============================================================================
3. DATA INTEGRATION (JOINS & STACKING)
==============================================================================
—- A. Joins using ‘dplyr’ —-
df_left <- df1 %>% left_join(df2, by = “id”) # Keeps all from df1, adds NAs for missing matches
df_inner <- df1 %>% inner_join(df2, by = “id”) # Keeps ONLY matching rows
df_right <- df1 %>% right_join(df2, by = “id”) # Keeps all from df2
df_full <- df1 %>% full_join(df2, by = “id”) # Keeps all rows from both datasets
Chaining multiple joins
combined_dplyr <- students %>%
left_join(academic, by = “student_id”) %>%
left_join(performance, by = “student_id”) %>%
arrange(student_id) # Sorts the final dataset by student_id
—- B. Joins using Base R —-
combined_base <- merge(df1, df2, by = “id”, all.x = TRUE) # Left Join
combined_base <- merge(df1, df2, by = “id”) # Inner Join (Default)
combined_base <- merge(df1, df2, by = “id”, all.y = TRUE) # Right Join
combined_base <- merge(df1, df2, by = “id”, all = TRUE) # Full Outer Join
Note: Base R ‘merge’ automatically sorts the output by the join key.
Check if two dataframes are identical: all.equal(df1, df2, check.attributes = FALSE)
—- C. Stacking & Concatenating —-
Vertical Stacking (Adding Rows)
stacked_base <- rbind(data_1, data_2)
stacked_dplyr <- bind_rows(data_1, data_2)
Horizontal Concatenation (Adding Columns – datasets must be ordered!)
concat_base <- cbind(data_3, data_4)
concat_dplyr <- bind_cols(data_3, data_4)
==============================================================================
4. MISSING VALUE HANDLING (NAs)
==============================================================================
—- A. Vectors —-
x <- c(NA, 4, 9, NA, 3, NA)
is.na(x) # Boolean check for NAs
sum(is.na(x)) # Count missing values
na.omit(x) # Remove NAs
mean(x, na.rm = TRUE) # Perform calculation ignoring NAs
x[is.na(x)] <- 0 # Replace NAs with 0
—- B. Dataframes —-
sum(is.na(df)) # Total missing values in whole dataset
colSums(is.na(df)) # Missing values per column
missing_prop <- colSums(is.na(df)) / nrow(df) # Missing proportion by column
df_no_missing <- na.omit(df) # Remove all rows with any missing values
—- C. Imputation (Base R) —-
Numeric (Mean or Median depending on skewness)
df$Age[is.na(df$Age)] <- median(df$Age, na.rm = TRUE)
Constant value
df$Cabin[is.na(df$Cabin)] <- “Unknown”
Categorical Mode Imputation
freq_category <- names(sort(table(df$Embarked), decreasing = TRUE))[1]
df$Embarked[is.na(df$Embarked)] <- freq_category
—- D. Imputation (dplyr) —-
df_clean <- df %>%
mutate(
Age = ifelse(is.na(Age), median(Age, na.rm = TRUE), Age),
Cabin = ifelse(is.na(Cabin), “Unknown”, Cabin),
Embarked = ifelse(is.na(Embarked), freq_category, Embarked)
)
==============================================================================
5. OUTLIER DETECTION & TREATMENT
==============================================================================
—- A. Visual Detection —-
Histogram for tails: ggplot(df, aes(x=var)) + geom_histogram()
Boxplot for spread: ggplot(df, aes(x=var)) + geom_boxplot()
Extracting outliers directly via Base R:
outliers_list <- boxplot(df$study_hours_weekly)$out
—- B. The IQR Method —-
target_var <- df$study_hours_weekly
Q1 <- quantile(target_var, 0.25, na.rm = TRUE)
Q3 <- quantile(target_var, 0.75, na.rm = TRUE)
iqr_val <- IQR(target_var, na.rm = TRUE) # Or simply Q3 – Q1
lower_bound <- Q1 – 1.5 * iqr_val
upper_bound <- Q3 + 1.5 * iqr_val
actual_outliers <- target_var[target_var < lower_bound | target_var > upper_bound]
—- C. Removing Outliers —-
Base R (Single column)
clean_df <- df[df$study_hours_weekly >= lower_bound & df$study_hours_weekly <= upper_bound, ]
Base R (Alternative)
clean_df_alt <- subset(df, study_hours_weekly >= lower_bound & study_hours_weekly <= upper_bound)
dplyr
clean_dplyr <- df %>% filter(study_hours_weekly >= lower_bound & study_hours_weekly <= upper_bound)
—- D. Capping Outliers —-
Capping replaces extreme values with the boundary limits, keeping row counts unchanged.
Base R
df$study_hours_weekly[df$study_hours_weekly < lower_bound] <- lower_bound
df$study_hours_weekly[df$study_hours_weekly > upper_bound] <- upper_bound
dplyr (pmin forces values down to upper bound, pmax forces values up to lower bound)
df_capped <- df %>%
mutate(
study_capped = pmin(pmax(study_hours_weekly, lower_bound), upper_bound)
)
==============================================================================
6. DATA TRANSFORMATIONS
==============================================================================
df_transformed <- df %>%
mutate(
# Log transformation compresses large values (use log(x + 1) if data contains zeros)
log_Time = log(Time_on_App_Minutes),
# Standardization (Z-score: Centers mean to 0, SD to 1)
# Must wrap in as.numeric() because scale() returns a matrix
z_Score = as.numeric(scale(Exam_Score))
)
==============================================================================
7. VISUALIZATIONS: GGPLOT2 FOUNDATIONS
==============================================================================
—- A. Preprocessing variables for plotting —-
Convert numeric codes into factors with clear labels before plotting
df <- df %>%
mutate(Approved = factor(Approved, levels = c(0, 1), labels = c(“Not approved”, “Approved”)))
Set up reusable themes and colors
col_blue <- “#2563EB”
col_orange <- “#F97316”
lecture_theme <- theme_minimal(base_size = 10) +
theme(
plot.title = element_text(face = “bold”, hjust = 0.5), # hjust=0.5 centers title
legend.position = “right” # “none” hides legend
)
—- B. Scatter & Bubble Plots —-
Scatter plot mapping a third variable to color
ggplot(df, aes(x = Income, y = Debt, color = Approved)) +
geom_point(alpha = 0.85, size = 3) +
scale_color_manual(values = c(“Not approved” = col_blue, “Approved” = col_orange)) +
labs(title = “Income vs Debt”, x = “Income”, y = “Debt”, color = “Loan Status”) +
lecture_theme
Bubble plot mapping a variable to size
ggplot(df, aes(x = Distance_km, y = Delivery_Time, size = Monthly_Spending, color = Membership)) +
geom_point(alpha = 0.65) +
scale_size(range = c(2, 10)) + # Controls the minimum and maximum bubble sizes
guides(size = “none”) + # Hides the size legend so it doesn’t clutter
lecture_theme
—- C. Bar Charts —-
Standard Bar (Counts observations automatically)
ggplot(df, aes(x = Approved)) + geom_bar(fill = “skyblue”, color = “black”)
Sorted / Summarized Bar Chart (Use geom_col when providing a Y value)
counts_df <- df %>% count(Education, sort = TRUE)
ggplot(counts_df, aes(x = reorder(Education, -n), y = n)) + # -n sorts descending
geom_col(fill = “orange”)
Horizontal Bar Chart (Flips the X and Y axes)
ggplot(counts_df, aes(x = reorder(Education, n), y = n)) +
geom_col(fill = “green”) +
coord_flip()
Stacked Bar Chart (Composition within groups)
ggplot(df, aes(x = Education, fill = Approved)) + geom_bar()
Dodged Bar Chart (Side-by-side comparison)
ggplot(df, aes(x = Gender, fill = Approved)) + geom_bar(position = “dodge”)
Percentage Bar Chart (Proportions)
ggplot(df, aes(x = Employ, fill = Approved)) +
geom_bar(position = “fill”) +
scale_y_continuous(labels = percent_format()) # Requires ‘scales’ library
Rotating X-Axis Labels for crowded charts
ggplot(df, aes(x = Creditcards_factor)) +
geom_bar() +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
—- D. Distributions (Histograms, Density, Boxplots) —-
Histogram
ggplot(df, aes(x = Income)) + geom_histogram(bins = 15, fill = “teal”, color = “black”)
Density Plot (Smoothed distribution)
ggplot(df, aes(x = Income, fill = Approved)) + geom_density(alpha = 0.5)
Comparative Boxplot (Spread & Outliers across groups)
stat_boxplot adds error bar lines to the whiskers
ggplot(df, aes(x = Approved, y = Income, fill = Approved)) +
stat_boxplot(geom = “errorbar”, width = 0.15) +
geom_boxplot(alpha = 0.85, color = “gray25”, width = 0.5)
==============================================================================
8. ADVANCED VISUALIZATIONS
==============================================================================
—- A. Static Maps (Choropleth) —-
world <- map_data(“world”)
south_asia <- subset(world, region %in% c(“India”, “Pakistan”, “Bangladesh”, “Sri Lanka”))
#
Merge geographic data with your metrics
south_asia_map <- south_asia %>% left_join(south_asia_density, by = “region”)
#
ggplot(south_asia_map, aes(x = long, y = lat, group = group, fill = density)) +
geom_polygon(color = “white”) +
coord_fixed() + # CRITICAL: Keeps X and Y axes proportional
scale_fill_gradient(low = “lightyellow”, high = “darkred”, name = “Density”) +
theme_minimal()
—- B. Correlograms —-
cor_matrix <- cor(mtcars)
corrplot(cor_matrix, type = “upper”, # Only shows upper triangle
method = “color”, # Uses colored squares
addCoef.col = “black”, # Adds text coefficients
number.cex = 0.6, # Size of coefficient text
tl.col = “black”, tl.srt = 45, # Rotates axis labels 45 degrees
col = colorRampPalette(c(“yellow”, “orange”, “red”))(100)) # 100 color shades
—- C. Heat Maps —-
Must transform from Wide to Long format first
heatmap_long <- pivot_longer(heatmap_df,
cols = c(Morning, Afternoon, Evening, Night),
names_to = “Time”, values_to = “Value”)
#
