################################################################################
#                                                                              #
#                  STA 4233 -- Intro-Program & Data Mgmt in R                  #
#                                FINAL PROJECT                                 #
#                                                                              #
#             Data Exploration and Cleaning: ABC Company Logistics             #
#                                                                              #
#  Author       : Matthew Ybarra                                               #
#  Submitted    : August 4, 2026                                               #
#                                                                              #
#  Purpose      : Read, join, clean, and explore the inbound shipment          #
#                 records in RawData.xlsx so that the relationship             #
#                 between ODM site, ship mode, and in-transit lead time        #
#                 can be modeled later.                                        #
#                                                                              #
#  Input        : RawData.xlsx -- worksheets "Raw-Data" and "Calendar".        #
#                 The workbook must sit in the R working directory.            #
#                 This script deliberately does not call setwd() and           #
#                 does not use an absolute path, so it runs unmodified         #
#                 on any machine.                                              #
#                                                                              #
#  Output       : ./Figures/*.png -- every figure used in the report           #
#                 ./Output/*.csv  -- descriptive stats and correlations        #
#                 Console summaries of every cleaning decision made.           #
#                                                                              #
################################################################################


################################################################################
# SECTION 0 -- ENVIRONMENT SETUP                                               #
################################################################################

# Clear the workspace so the script always runs from a known, empty state.
rm(list = ls())

# Keep the console output readable and stop numbers printing in scientific form.
options(stringsAsFactors = FALSE, scipen = 999)

# Fix the random seed. Nothing below is random today, but seeding protects the
# reproducibility of the results if a stochastic imputation is added later.
set.seed(4233)


################################################################################
# SECTION 1 -- USER DEFINED FUNCTIONS                                          #
#                                                                              #
# Seven helper functions are defined here and every one of them is used later  #
# in the script. Defining them once keeps the cleaning logic consistent across #
# columns and makes each rule easy to audit.                                   #
################################################################################

#-------------------------------------------------------------------------------
# ensure_packages()
#
# Loads each required package and installs it first if it is not already
# available. This lets the script run start-to-finish on a machine that has
# never seen these packages before.
#
# Arguments : pkgs - character vector of package names.
# Returns   : nothing; called for its side effect of attaching the packages.
#-------------------------------------------------------------------------------
ensure_packages <- function(pkgs) {
  for (p in pkgs) {
    if (!requireNamespace(p, quietly = TRUE)) {
      message("Installing missing package: ", p)
      install.packages(p, repos = "https://cloud.r-project.org")
    }
    suppressPackageStartupMessages(library(p, character.only = TRUE))
  }
  invisible(NULL)
}

#-------------------------------------------------------------------------------
# assign_calendar_period()
#
# Matches each date to the fiscal period that contains it by testing the date
# against the start/end range of every row of the Calendar worksheet. This is a
# "non-equi" join: the match is made by a BETWEEN comparison rather than by an
# equality on a key column.
#
# No date literal appears anywhere in this function. Every boundary is read
# from the Calendar worksheet at run time, so the script keeps working if the
# company revises its fiscal calendar.
#
# Arguments : dates     - vector of dates to be labeled.
#             calendar  - data frame holding the calendar worksheet.
#             start_col, end_col, quarter_col, year_col - column names in
#                         'calendar' that hold the range and the labels.
# Returns   : data frame with one row per input date and columns Quarter/Year.
#             A date that falls outside every published range returns NA.
#-------------------------------------------------------------------------------
assign_calendar_period <- function(dates, calendar,
                                   start_col   = "start_date",
                                   end_col     = "end_date",
                                   quarter_col = "quarter",
                                   year_col    = "year") {

  starts <- as.Date(calendar[[start_col]])
  ends   <- as.Date(calendar[[end_col]])
  dates  <- as.Date(dates)

  # For each date, find the index of the calendar row whose range contains it.
  idx <- vapply(dates, function(d) {
    if (is.na(d)) return(NA_integer_)
    hit <- which(d >= starts & d <= ends)
    if (length(hit) == 0) NA_integer_ else hit[1]
  }, FUN.VALUE = integer(1))

  data.frame(
    quarter = calendar[[quarter_col]][idx],
    year    = calendar[[year_col]][idx]
  )
}

#-------------------------------------------------------------------------------
# standardize_label()
#
# Puts a categorical column into a single canonical form before its values are
# validated. Leading/trailing blanks are stripped, runs of internal whitespace
# are collapsed to one space, and the text is upper-cased so that "air",
# "Air " and "AIR" all become the same level. An optional lookup table then
# folds known spelling variants onto the approved label.
#
# Arguments : x       - character vector to standardize.
#             recode  - named character vector; names are the variants found in
#                       the data, values are the approved labels.
# Returns   : standardized character vector of the same length.
#-------------------------------------------------------------------------------
standardize_label <- function(x, recode = NULL) {
  x <- toupper(trimws(as.character(x)))
  x <- gsub("[[:space:]]+", " ", x)

  # Treat common placeholder text as genuinely missing rather than as a level.
  x[x %in% c("", "NA", "N/A", "NULL", "NONE", "-", "?", "UNKNOWN")] <- NA

  if (!is.null(recode)) {
    hit <- x %in% names(recode)
    x[hit] <- recode[x[hit]]
  }
  x
}

#-------------------------------------------------------------------------------
# flag_far_out()
#
# Flags "far out" values using Tukey's fences at k inter-quartile ranges beyond
# the first and third quartiles. k = 3 (rather than the usual 1.5) is used
# because the business question is about delayed shipments: a moderately long
# lead time is the signal ABC wants to study, not noise to be scrubbed away.
# Only genuinely implausible observations should be replaced.
#
# The min_n guard stops the rule firing on a group too small to estimate
# quartiles reliably, and the zero-IQR guard stops it firing on a group whose
# values are nearly all identical. In both cases nothing is flagged.
#
# Arguments : x     - numeric vector (already screened for logical violations).
#             k     - fence multiplier.
#             min_n - smallest group size the rule is allowed to act on.
# Returns   : logical vector, TRUE where the value lies beyond the fences.
#-------------------------------------------------------------------------------
flag_far_out <- function(x, k = 3, min_n = 30) {
  valid <- x[!is.na(x)]
  if (length(valid) < min_n) return(rep(FALSE, length(x)))

  q   <- stats::quantile(valid, c(0.25, 0.75), names = FALSE)
  iqr <- q[2] - q[1]
  if (iqr <= 0) return(rep(FALSE, length(x)))

  lower <- q[1] - k * iqr
  upper <- q[2] + k * iqr
  !is.na(x) & (x < lower | x > upper)
}

#-------------------------------------------------------------------------------
# impute_median()
#
# Replaces missing values with the median of the non-missing values supplied.
# Called inside a grouped mutate() so the median is the group's median. If an
# entire group is missing, the caller's fallback value is used instead. The
# median is preferred over the mean because lead times are right-skewed, and
# the result is rounded because a lead time is a whole number of days.
#
# Arguments : x        - numeric vector containing NAs to fill.
#             fallback - value to use when every element of x is NA.
# Returns   : numeric vector with no NAs.
#-------------------------------------------------------------------------------
impute_median <- function(x, fallback = NA_real_) {
  m <- suppressWarnings(stats::median(x, na.rm = TRUE))
  if (is.na(m)) m <- fallback
  x[is.na(x)] <- m
  round(x)
}

#-------------------------------------------------------------------------------
# describe_numeric()
#
# Builds the descriptive statistics table reported for every numeric variable.
#
# Arguments : df   - data frame.
#             vars - character vector of numeric column names to describe.
# Returns   : data frame, one row per variable.
#-------------------------------------------------------------------------------
describe_numeric <- function(df, vars) {
  do.call(rbind, lapply(vars, function(v) {
    x  <- df[[v]]
    xs <- x[!is.na(x)]
    data.frame(
      Variable = v,
      N        = length(xs),
      Missing  = sum(is.na(x)),
      Mean     = round(mean(xs), 2),
      SD       = round(stats::sd(xs), 2),
      Min      = min(xs),
      Q1       = stats::quantile(xs, 0.25, names = FALSE),
      Median   = stats::median(xs),
      Q3       = stats::quantile(xs, 0.75, names = FALSE),
      Max      = max(xs),
      IQR      = stats::IQR(xs)
    )
  }))
}

#-------------------------------------------------------------------------------
# describe_categorical()
#
# Builds the frequency table reported for every categorical variable.
#
# Arguments : df   - data frame.
#             vars - character vector of categorical column names.
# Returns   : data frame of level counts and percentages, stacked by variable.
#-------------------------------------------------------------------------------
describe_categorical <- function(df, vars) {
  do.call(rbind, lapply(vars, function(v) {
    tb <- table(df[[v]], useNA = "ifany")
    data.frame(
      Variable = v,
      Level    = names(tb),
      Count    = as.integer(tb),
      Percent  = round(100 * as.integer(tb) / sum(tb), 2)
    )
  }))
}


################################################################################
# SECTION 2 -- LOAD PACKAGES AND PREPARE OUTPUT FOLDERS                        #
################################################################################

ensure_packages(c("readxl", "dplyr", "tidyr", "ggplot2",
                  "fastDummies", "corrplot"))

# Figures and tables are written beside the script, inside the working
# directory, so nothing outside the project folder is touched.
dir.create("Figures", showWarnings = FALSE)
dir.create("Output",  showWarnings = FALSE)

# Shared plot theme so every figure in the report looks the same.
theme_abc <- theme_bw(base_size = 12) +
  theme(plot.title    = element_text(face = "bold", size = 13),
        plot.subtitle = element_text(colour = "grey30", size = 10),
        legend.position = "bottom")


################################################################################
# SECTION 3 -- READ THE RAW WORKBOOK                                           #
#                                                                              #
# Requirement 1a: read both worksheets, with no hard coded working directory.  #
################################################################################

raw_data <- readxl::read_excel("RawData.xlsx", sheet = "Raw-Data")
calendar <- readxl::read_excel("RawData.xlsx", sheet = "Calendar")

# Record the size of the delivered file. This figure is quoted in the report.
n_rows_received <- nrow(raw_data)

cat("\n=================== RAW DATA AS RECEIVED ===================\n")
cat("Rows received in Raw-Data :", n_rows_received, "\n")
cat("Columns received          :", ncol(raw_data), "\n\n")
print(utils::str(raw_data))

# Rename to lower-case, underscore-separated names. The original headers carry
# embedded spaces, which force back-tick quoting throughout the script.
names(raw_data) <- c("lob", "origin", "ship_mode",
                     "po_download_date", "ship_date", "receipt_date")
names(calendar) <- c("s_no", "start_date", "end_date", "quarter", "year")

# readxl returns the date columns as POSIXct. Converting to Date removes the
# time-of-day component so that differences are exact whole days.
raw_data <- raw_data %>%
  mutate(across(c(po_download_date, ship_date, receipt_date), as.Date))

calendar <- calendar %>%
  mutate(across(c(start_date, end_date), as.Date))

cat("\n--- Calendar worksheet (fiscal period definitions) ---\n")
print(calendar)

# Missing value audit of the file exactly as delivered.
missing_raw <- data.frame(
  Column          = names(raw_data),
  Missing_Count   = sapply(raw_data, function(x) sum(is.na(x))),
  Missing_Percent = round(100 * sapply(raw_data,
                            function(x) mean(is.na(x))), 2),
  row.names = NULL
)
cat("\n--- Missing values in the file as received ---\n")
print(missing_raw)


################################################################################
# SECTION 4 -- ADD QUARTER AND YEAR                                            #
#                                                                              #
# Requirement 1b: label every shipment with the fiscal quarter and year that   #
# contains its Receipt Date, taking every boundary from the Calendar sheet.    #
################################################################################

periods <- assign_calendar_period(raw_data$receipt_date, calendar)

raw_data <- raw_data %>%
  mutate(quarter = periods$quarter,
         year    = periods$year)

cat("\n=================== QUARTER / YEAR ASSIGNMENT ===================\n")
cat("Receipt dates present but unmatched by the calendar :",
    sum(!is.na(raw_data$receipt_date) & is.na(raw_data$quarter)), "\n")
cat("Rows with no quarter because Receipt Date is missing:",
    sum(is.na(raw_data$receipt_date)), "\n\n")
print(table(raw_data$quarter, raw_data$year, useNA = "ifany"))


################################################################################
# SECTION 5 -- CALCULATE THE TWO LEAD TIMES                                    #
#                                                                              #
# Requirement 1c.                                                              #
#   Manufacturing Lead Time = Ship Date    - PO Download Date                  #
#   In-transit  Lead Time   = Receipt Date - Ship Date                         #
################################################################################

raw_data <- raw_data %>%
  mutate(
    manufacturing_lead_time = as.numeric(ship_date - po_download_date),
    in_transit_lead_time    = as.numeric(receipt_date - ship_date)
  )

cat("\n=================== LEAD TIMES BEFORE CLEANING ===================\n")
print(describe_numeric(raw_data,
                       c("in_transit_lead_time", "manufacturing_lead_time")))

# Both distributions are impossible as calculated: a shipment cannot be
# received before it leaves the factory, and a product cannot ship before its
# purchase order exists. Quantify each violation before repairing anything.
cat("\nIn-transit lead time below zero      :",
    sum(raw_data$in_transit_lead_time < 0, na.rm = TRUE), "\n")
cat("Manufacturing lead time below zero   :",
    sum(raw_data$manufacturing_lead_time < 0, na.rm = TRUE), "\n")
cat("Manufacturing lead time above 100 d  :",
    sum(raw_data$manufacturing_lead_time > 100, na.rm = TRUE), "\n")

# The two problems overlap almost perfectly, which identifies the guilty
# column: a Ship Date recorded far too late inflates the manufacturing lead
# time and simultaneously drives the in-transit lead time negative.
cat("Rows failing BOTH tests (negative in-transit AND >100 day build):",
    sum(raw_data$in_transit_lead_time < 0 &
        raw_data$manufacturing_lead_time > 100, na.rm = TRUE), "\n")

# Keep an untouched copy so the report can show before-and-after distributions.
raw_uncleaned <- raw_data


################################################################################
# SECTION 6 -- CLEAN THE CATEGORICAL COLUMNS                                   #
#                                                                              #
# Requirement 1d, for LOB, Origin, Ship Mode and Quarter.                      #
################################################################################

# The labels ABC's operations model recognises. Anything else is invalid.
valid_lob       <- c("PRODUCT A", "PRODUCT B", "PRODUCT C")
valid_origin    <- c("SITE A", "SITE B", "SITE C", "SITE D")
valid_ship_mode <- c("AIR", "FASTBOAT", "GROUND", "OCEAN")
valid_quarter   <- c("Q1", "Q2", "Q3", "Q4")

# Known spelling variants that should be folded onto an approved label rather
# than discarded. "FAST BOAT" and "FASTBOAT" are the same service.
ship_mode_recode <- c("FAST BOAT" = "FASTBOAT", "FAST-BOAT" = "FASTBOAT",
                      "BOAT" = "FASTBOAT", "AIR FREIGHT" = "AIR",
                      "SEA" = "OCEAN", "TRUCK" = "GROUND",
                      "ROAD" = "GROUND")
origin_recode    <- c("SITEA" = "SITE A", "SITEB" = "SITE B",
                      "SITEC" = "SITE C", "SITED" = "SITE D")
lob_recode       <- c("PRODUCTA" = "PRODUCT A", "PRODUCTB" = "PRODUCT B",
                      "PRODUCTC" = "PRODUCT C")

raw_data <- raw_data %>%
  mutate(
    lob       = standardize_label(lob,       lob_recode),
    origin    = standardize_label(origin,    origin_recode),
    ship_mode = standardize_label(ship_mode, ship_mode_recode),
    quarter   = standardize_label(quarter)
  )

# Any value that survived standardization but is still not an approved label is
# an invalid category and is set to NA so that it is imputed with the rest.
raw_data <- raw_data %>%
  mutate(
    lob       = ifelse(lob       %in% valid_lob,       lob,       NA),
    origin    = ifelse(origin    %in% valid_origin,    origin,    NA),
    ship_mode = ifelse(ship_mode %in% valid_ship_mode, ship_mode, NA),
    quarter   = ifelse(quarter   %in% valid_quarter,   quarter,   NA)
  )

cat("\n=================== CATEGORICAL COLUMN AUDIT ===================\n")
cat("Invalid or missing LOB values      :", sum(is.na(raw_data$lob)), "\n")
cat("Invalid or missing Origin values   :", sum(is.na(raw_data$origin)), "\n")
cat("Invalid or missing Ship Mode values:", sum(is.na(raw_data$ship_mode)), "\n")
cat("Missing Quarter values (no receipt):", sum(is.na(raw_data$quarter)), "\n")
cat("\nLevels retained after standardization:\n")
print(lapply(raw_data[c("lob", "origin", "ship_mode", "quarter")],
             function(x) sort(unique(x[!is.na(x)]))))

# Origin and ship mode are close to being a single fixed route: each site uses
# essentially one carrier service. This cross-tabulation justifies grouping the
# lead-time imputation by Origin x Ship Mode later in the script.
cat("\n--- Shipment counts by Origin and Ship Mode ---\n")
print(table(raw_data$origin, raw_data$ship_mode, useNA = "ifany"))


################################################################################
# SECTION 7 -- REMOVE ROWS THAT ARE MOSTLY MISSING                             #
#                                                                              #
# Requirement 1e: whole rows may be deleted only when they are mostly NA.      #
# Everything else must be imputed.                                             #
#                                                                              #
# The four fields that carry the analysis are Quarter, Year, In-transit Lead   #
# Time and Manufacturing Lead Time. A row missing at least half of them cannot #
# contribute to the study and is dropped; every other gap is filled below.     #
################################################################################

analysis_fields <- c("quarter", "year",
                     "in_transit_lead_time", "manufacturing_lead_time")

raw_data <- raw_data %>%
  mutate(na_share = rowMeans(is.na(across(all_of(analysis_fields)))))

rows_to_drop    <- raw_data$na_share >= 0.5
n_rows_removed  <- sum(rows_to_drop)

cat("\n=================== ROW REMOVAL ===================\n")
cat("Rows missing at least half of the analysis fields:", n_rows_removed, "\n")
cat("Distribution of the missing share across all rows:\n")
print(table(round(raw_data$na_share, 2)))

clean_data <- raw_data %>%
  filter(!rows_to_drop) %>%
  select(-na_share)

n_rows_analyzed <- nrow(clean_data)
cat("Rows carried forward for cleaning and modeling   :", n_rows_analyzed, "\n")


################################################################################
# SECTION 8 -- CLEAN THE TWO LEAD TIME COLUMNS                                 #
#                                                                              #
# Requirement 1d/1e. Values are invalidated in two passes and then imputed.    #
#                                                                              #
#   Pass 1  Logical violation. A negative lead time is physically impossible   #
#           and is always an error, whatever its size.                         #
#   Pass 2  Statistical far-outlier. Values beyond 3 IQR of their own          #
#           Origin x Ship Mode group are implausible for that route. Grouping  #
#           matters: 40 days is routine by ocean and impossible by ground, so  #
#           a single global fence would be wrong for both.                     #
#                                                                              #
# Pass 1 runs first so that the impossible values cannot distort the quartiles #
# that Pass 2 depends on.                                                      #
################################################################################

# --- Pass 1: logical violations -----------------------------------------------
n_negative_transit <- sum(clean_data$in_transit_lead_time    < 0, na.rm = TRUE)
n_negative_mfg     <- sum(clean_data$manufacturing_lead_time < 0, na.rm = TRUE)

clean_data <- clean_data %>%
  mutate(
    in_transit_lead_time    = ifelse(in_transit_lead_time    < 0, NA,
                                     in_transit_lead_time),
    manufacturing_lead_time = ifelse(manufacturing_lead_time < 0, NA,
                                     manufacturing_lead_time)
  )

# --- Pass 2: far-outliers within each shipping route --------------------------
clean_data <- clean_data %>%
  group_by(origin, ship_mode) %>%
  mutate(
    transit_outlier = flag_far_out(in_transit_lead_time),
    mfg_outlier     = flag_far_out(manufacturing_lead_time)
  ) %>%
  ungroup()

n_outlier_transit <- sum(clean_data$transit_outlier)
n_outlier_mfg     <- sum(clean_data$mfg_outlier)

clean_data <- clean_data %>%
  mutate(
    in_transit_lead_time    = ifelse(transit_outlier, NA, in_transit_lead_time),
    manufacturing_lead_time = ifelse(mfg_outlier,     NA, manufacturing_lead_time)
  )

# --- Impute every invalidated value -------------------------------------------
# The replacement is the median of the shipment's own Origin x Ship Mode group,
# which respects the very different speed of each route.
global_transit_median <- stats::median(clean_data$in_transit_lead_time,
                                       na.rm = TRUE)
global_mfg_median     <- stats::median(clean_data$manufacturing_lead_time,
                                       na.rm = TRUE)

n_imputed_transit <- sum(is.na(clean_data$in_transit_lead_time))
n_imputed_mfg     <- sum(is.na(clean_data$manufacturing_lead_time))

clean_data <- clean_data %>%
  group_by(origin, ship_mode) %>%
  mutate(
    in_transit_lead_time    = impute_median(in_transit_lead_time,
                                            global_transit_median),
    manufacturing_lead_time = impute_median(manufacturing_lead_time,
                                            global_mfg_median)
  ) %>%
  ungroup() %>%
  select(-transit_outlier, -mfg_outlier)

cat("\n=================== LEAD TIME CLEANING ===================\n")
cat("In-transit    : negative values invalidated  :", n_negative_transit, "\n")
cat("In-transit    : far-outliers invalidated     :", n_outlier_transit, "\n")
cat("In-transit    : values imputed in total      :", n_imputed_transit,
    sprintf("(%.2f%% of retained rows)\n",
            100 * n_imputed_transit / n_rows_analyzed))
cat("Manufacturing : negative values invalidated  :", n_negative_mfg, "\n")
cat("Manufacturing : far-outliers invalidated     :", n_outlier_mfg, "\n")
cat("Manufacturing : values imputed in total      :", n_imputed_mfg,
    sprintf("(%.2f%% of retained rows)\n",
            100 * n_imputed_mfg / n_rows_analyzed))

# Confirm the cleaning actually worked before any analysis is run on the result.
stopifnot(
  !any(is.na(clean_data$in_transit_lead_time)),
  !any(is.na(clean_data$manufacturing_lead_time)),
  all(clean_data$in_transit_lead_time    >= 0),
  all(clean_data$manufacturing_lead_time >= 0),
  !any(is.na(clean_data$lob)),
  !any(is.na(clean_data$origin)),
  !any(is.na(clean_data$ship_mode)),
  !any(is.na(clean_data$quarter)),
  !any(is.na(clean_data$year))
)
cat("\nValidation passed: no missing or out-of-range values remain.\n")


################################################################################
# SECTION 9 -- RECONCILIATION OF THE ROW COUNT                                 #
#                                                                              #
# The report must state how many rows arrived, how many were removed, and how  #
# many were analyzed. That reconciliation is produced here.                    #
################################################################################

row_audit <- data.frame(
  Stage = c("Rows received in Raw-Data",
            "Rows removed (mostly missing)",
            "Rows retained for modeling",
            "In-transit lead times imputed",
            "Manufacturing lead times imputed"),
  Rows  = c(n_rows_received, n_rows_removed, n_rows_analyzed,
            n_imputed_transit, n_imputed_mfg)
)
row_audit$Percent_of_Received <- round(100 * row_audit$Rows / n_rows_received, 2)

cat("\n=================== ROW RECONCILIATION ===================\n")
print(row_audit)
write.csv(row_audit, "Output/row_audit.csv", row.names = FALSE)


################################################################################
# SECTION 10 -- NUMERIC EXPLORATION                                            #
#                                                                              #
# Requirement 1f, numeric half.                                                #
################################################################################

numeric_vars     <- c("in_transit_lead_time", "manufacturing_lead_time", "year")
categorical_vars <- c("lob", "origin", "ship_mode", "quarter")

desc_numeric <- describe_numeric(clean_data, numeric_vars)
desc_categ   <- describe_categorical(clean_data, categorical_vars)

cat("\n=================== DESCRIPTIVE STATISTICS ===================\n")
print(desc_numeric)
cat("\n")
print(desc_categ)

write.csv(desc_numeric, "Output/descriptive_numeric.csv",     row.names = FALSE)
write.csv(desc_categ,   "Output/descriptive_categorical.csv", row.names = FALSE)

# Mean in-transit lead time on every route actually used. This table is the
# operational heart of the report: it is what ABC would quote to a customer.
route_summary <- clean_data %>%
  group_by(origin, ship_mode) %>%
  summarise(Shipments = n(),
            Mean      = round(mean(in_transit_lead_time), 2),
            SD        = round(stats::sd(in_transit_lead_time), 2),
            Median    = stats::median(in_transit_lead_time),
            Min       = min(in_transit_lead_time),
            Max       = max(in_transit_lead_time),
            .groups   = "drop") %>%
  arrange(desc(Mean))

cat("\n--- In-transit lead time by shipping route ---\n")
print(as.data.frame(route_summary))
write.csv(route_summary, "Output/route_summary.csv", row.names = FALSE)

# Movement over time. This is where the pandemic disruption should show up.
quarter_summary <- clean_data %>%
  group_by(year, quarter) %>%
  summarise(Shipments = n(),
            Mean_In_Transit = round(mean(in_transit_lead_time), 2),
            Mean_Manufacturing = round(mean(manufacturing_lead_time), 2),
            .groups = "drop") %>%
  arrange(year, quarter)

cat("\n--- Lead times by fiscal quarter ---\n")
print(as.data.frame(quarter_summary))
write.csv(quarter_summary, "Output/quarter_summary.csv", row.names = FALSE)


################################################################################
# SECTION 11 -- GRAPHICAL EXPLORATION                                          #
#                                                                              #
# Requirement 1f, graphical half. Every figure is saved to ./Figures.          #
################################################################################

# --- Figure 1: the effect of cleaning on the in-transit distribution ----------
before_after <- rbind(
  data.frame(stage = "Before cleaning",
             value = raw_uncleaned$in_transit_lead_time),
  data.frame(stage = "After cleaning",
             value = clean_data$in_transit_lead_time)
)
# Drop the 145 rows that had no lead time at all so the histogram does not
# warn about non-finite values it cannot place on the axis.
before_after <- before_after[!is.na(before_after$value), ]
before_after$stage <- factor(before_after$stage,
                             levels = c("Before cleaning", "After cleaning"))

# A boxplot is used rather than a histogram because the corrupted values reach
# -235 days: on a shared histogram axis those 95 records are too few to be
# visible, whereas a boxplot plots each one as a point and makes the span of
# the contamination obvious at a glance.
fig1 <- ggplot(before_after, aes(x = stage, y = value, fill = stage)) +
  geom_boxplot(show.legend = FALSE, outlier.alpha = 0.35,
               outlier.colour = "grey25") +
  geom_hline(yintercept = 0, linetype = "dashed", colour = "grey40") +
  coord_flip() +
  scale_fill_manual(values = c("Before cleaning" = "#c0504d",
                               "After cleaning"  = "#4f81bd")) +
  labs(title = "In-Transit Lead Time Before and After Cleaning",
       subtitle = paste("Values below the dashed zero line are impossible;",
                        "they were caused by Ship Dates recorded after the",
                        "Receipt Date"),
       x = NULL, y = "In-transit lead time (days)") +
  theme_abc
ggsave("Figures/fig1_cleaning_effect.png", fig1,
       width = 9, height = 4.5, dpi = 150)

# --- Figure 2: distribution of in-transit lead time after cleaning -----------
fig2 <- ggplot(clean_data, aes(x = in_transit_lead_time)) +
  geom_histogram(binwidth = 2, fill = "#4f81bd", colour = "white") +
  geom_vline(xintercept = mean(clean_data$in_transit_lead_time),
             linetype = "dashed", linewidth = 0.8, colour = "#c0504d") +
  labs(title = "Distribution of In-Transit Lead Time",
       subtitle = paste0("Dashed line marks the mean of ",
                         round(mean(clean_data$in_transit_lead_time), 1),
                         " days; the distribution is strongly right-skewed"),
       x = "In-transit lead time (days)", y = "Number of shipments") +
  theme_abc
ggsave("Figures/fig2_transit_distribution.png", fig2,
       width = 8, height = 5, dpi = 150)

# --- Figure 3: in-transit lead time by ship mode ------------------------------
fig3 <- ggplot(clean_data, aes(x = reorder(ship_mode, in_transit_lead_time,
                                           FUN = median),
                               y = in_transit_lead_time, fill = ship_mode)) +
  geom_boxplot(show.legend = FALSE, outlier.alpha = 0.25) +
  labs(title = "In-Transit Lead Time by Ship Mode",
       subtitle = "Ship mode separates the lead-time distribution more sharply than any other factor",
       x = "Ship mode", y = "In-transit lead time (days)") +
  theme_abc
ggsave("Figures/fig3_transit_by_shipmode.png", fig3,
       width = 8, height = 5, dpi = 150)

# --- Figure 4: in-transit lead time by origin site ----------------------------
fig4 <- ggplot(clean_data, aes(x = reorder(origin, in_transit_lead_time,
                                           FUN = median),
                               y = in_transit_lead_time, fill = origin)) +
  geom_boxplot(show.legend = FALSE, outlier.alpha = 0.25) +
  labs(title = "In-Transit Lead Time by ODM Site",
       subtitle = "Each site is served by a different mix of carrier services",
       x = "ODM site", y = "In-transit lead time (days)") +
  theme_abc
ggsave("Figures/fig4_transit_by_origin.png", fig4,
       width = 8, height = 5, dpi = 150)

# --- Figure 5: lead times over the fiscal calendar ----------------------------
quarter_long <- quarter_summary %>%
  mutate(period = paste(quarter, year)) %>%
  tidyr::pivot_longer(cols = c(Mean_In_Transit, Mean_Manufacturing),
                      names_to = "measure", values_to = "days") %>%
  mutate(measure = recode(measure,
                          Mean_In_Transit    = "In-transit",
                          Mean_Manufacturing = "Manufacturing"))

fig5 <- ggplot(quarter_long, aes(x = period, y = days,
                                 colour = measure, group = measure)) +
  geom_line(linewidth = 1) +
  geom_point(size = 2.5) +
  labs(title = "Average Lead Time by Fiscal Quarter",
       subtitle = "Both stages lengthened through 2020, but in-transit time rose far more sharply",
       x = "Fiscal period", y = "Mean lead time (days)", colour = NULL) +
  theme_abc
ggsave("Figures/fig5_leadtime_by_quarter.png", fig5,
       width = 8, height = 5, dpi = 150)

# --- Figure 6: shipment volume by site and mode -------------------------------
fig6 <- ggplot(clean_data, aes(x = origin, fill = ship_mode)) +
  geom_bar() +
  labs(title = "Shipment Volume by ODM Site and Ship Mode",
       subtitle = "Each site relies on essentially one carrier service",
       x = "ODM site", y = "Number of shipments", fill = "Ship mode") +
  theme_abc
ggsave("Figures/fig6_volume_by_site_mode.png", fig6,
       width = 8, height = 5, dpi = 150)

# --- Figure 7: relationship between the two lead times ------------------------
fig7 <- ggplot(clean_data, aes(x = manufacturing_lead_time,
                               y = in_transit_lead_time)) +
  geom_jitter(alpha = 0.15, width = 0.3, height = 0.3, colour = "#4f81bd") +
  geom_smooth(method = "lm", formula = y ~ x, se = FALSE, colour = "#c0504d") +
  labs(title = "In-Transit Versus Manufacturing Lead Time",
       subtitle = "Moderate positive association: routes that build slowly also ship slowly",
       x = "Manufacturing lead time (days)",
       y = "In-transit lead time (days)") +
  theme_abc
ggsave("Figures/fig7_transit_vs_manufacturing.png", fig7,
       width = 8, height = 5, dpi = 150)

# --- Figure 8: lead time by product line --------------------------------------
fig8 <- ggplot(clean_data, aes(x = lob, y = in_transit_lead_time, fill = lob)) +
  geom_boxplot(show.legend = FALSE, outlier.alpha = 0.25) +
  labs(title = "In-Transit Lead Time by Line of Business",
       subtitle = "Product line has little influence once the route is fixed",
       x = "Line of business", y = "In-transit lead time (days)") +
  theme_abc
ggsave("Figures/fig8_transit_by_lob.png", fig8,
       width = 8, height = 5, dpi = 150)


################################################################################
# SECTION 12 -- ONE-HOT ENCODING AND CORRELATIONS                              #
#                                                                              #
# Requirement 1g. Correlation requires numeric input, so LOB, Origin, Ship     #
# Mode and Quarter are one-hot encoded: each level becomes its own 0/1         #
# indicator column, which lets a categorical level correlate with lead time    #
# without implying any false ordering between the levels.                      #
################################################################################

model_data <- clean_data %>%
  select(lob, origin, ship_mode, quarter, year,
         manufacturing_lead_time, in_transit_lead_time)

encoded_data <- fastDummies::dummy_cols(
  model_data,
  select_columns          = c("lob", "origin", "ship_mode", "quarter"),
  remove_selected_columns = TRUE
)

# Tidy the generated indicator names so the correlation table reads cleanly.
names(encoded_data) <- gsub(" ", "_", names(encoded_data))

cat("\n=================== ONE-HOT ENCODED MATRIX ===================\n")
cat("Variables entering the correlation analysis:", ncol(encoded_data), "\n")
print(names(encoded_data))

# Full correlation matrix across every variable pair.
cor_matrix <- stats::cor(encoded_data, use = "complete.obs")
write.csv(round(cor_matrix, 3), "Output/correlation_matrix.csv")

# Each predictor's correlation with the response, sorted by strength.
cor_with_transit <- data.frame(
  Predictor   = rownames(cor_matrix),
  Correlation = round(cor_matrix[, "in_transit_lead_time"], 3),
  row.names   = NULL
) %>%
  filter(Predictor != "in_transit_lead_time") %>%
  arrange(desc(abs(Correlation)))

cat("\n--- Correlation with in-transit lead time, strongest first ---\n")
print(cor_with_transit)
write.csv(cor_with_transit, "Output/correlation_with_in_transit.csv",
          row.names = FALSE)

# --- Figure 9: correlation matrix --------------------------------------------
png("Figures/fig9_correlation_matrix.png",
    width = 1400, height = 1400, res = 150)
corrplot::corrplot(cor_matrix,
                   method      = "color",
                   type        = "upper",
                   order       = "hclust",
                   tl.col      = "black",
                   tl.srt      = 45,
                   tl.cex      = 0.75,
                   addCoef.col = "grey20",
                   number.cex  = 0.5,
                   diag        = FALSE,
                   title = "Correlation Matrix of All Modeling Variables",
                   mar = c(0, 0, 2, 0))
dev.off()

# --- Figure 10: correlation with the response, ranked -------------------------
fig10 <- ggplot(cor_with_transit,
                aes(x = reorder(Predictor, Correlation), y = Correlation,
                    fill = Correlation > 0)) +
  geom_col(show.legend = FALSE) +
  geom_hline(yintercept = 0, colour = "grey40") +
  coord_flip() +
  scale_fill_manual(values = c("TRUE" = "#4f81bd", "FALSE" = "#c0504d")) +
  labs(title = "Correlation of Each Predictor With In-Transit Lead Time",
       subtitle = "Ocean and fast-boat service lengthen transit; ground and air shorten it",
       x = NULL, y = "Pearson correlation") +
  theme_abc
ggsave("Figures/fig10_correlation_ranked.png", fig10,
       width = 8, height = 7, dpi = 150)


################################################################################
# SECTION 13 -- EXPORT THE ANALYSIS DATA SET                                   #
################################################################################

write.csv(clean_data, "Output/clean_data.csv", row.names = FALSE)

cat("\n=================== SCRIPT COMPLETE ===================\n")
cat("Rows received :", n_rows_received, "\n")
cat("Rows removed  :", n_rows_removed, "\n")
cat("Rows analyzed :", n_rows_analyzed, "\n")
cat("Figures written to ./Figures and tables to ./Output\n")

################################################################################
#                                END OF SCRIPT                                 #
################################################################################
