##########################################################
# Install and Test R Packages                            #
# Data Analytics in Marketing - All Chapter Examples     #
##########################################################

# Run this script once, from top to bottom, before the first class example.
# It installs every package used in the R chapter examples (only the ones you
# are missing) and then checks that each package loads. The last lines print
# a report. If every package says "OK", R is set up correctly.
#
# Installing everything can take several minutes the first time.
# If R asks "Do you want to install from sources the packages which need
# compilation?", answer "no" (n).

## Step 1: Check your version of R
## The examples were tested with R 4.6.1. Any recent version (4.3 or later) should work.
cat("Your R version:", R.version.string, "\n")
if (getRversion() < "4.3.0") {
  cat("WARNING: Your version of R is older than 4.3.0. Please install the latest",
      "version of R from https://cran.r-project.org before continuing.\n")
}

## Step 2: List of packages used in the chapter examples
packages <- c(
  "dplyr",        # Chapters 3, 4, 5, 7, 9, 11, 16 - data manipulation
  "tidyr",        # Chapters 3, 4, 11, 15, 16 - reshaping tables
  "ggplot2",      # Chapters 3, 4, 5, 7, 8, 9, 11, 12, 13, 15, 16 - plots and maps
  "scales",       # Chapters 7, 9, 15, 16 - formatting numbers ($, %, commas)
  "MASS",         # Chapter 4 - discriminant analysis
  "sf",           # Chapters 3, 4 - maps
  "tigris",       # Chapters 3, 4 - zip code and state boundaries
  "ggrepel",      # Chapter 5 - labels on the perceptual maps
  "GPArotation",  # Chapter 11 - oblique factor rotation
  "conjoint",     # Chapter 12 - conjoint analysis
  "tseries",      # Chapter 15 - unit root (Dickey-Fuller) test
  "MatchIt",      # Chapter 16 - propensity score matching
  "AER",          # Chapter 16 - Tobit model
  "stm",          # Chapter 17 - structural topic model
  "tm",           # Chapter 17 - text processing
  "Rtsne",        # Chapter 17 - choosing the number of topics
  "rsvd",         # Chapter 17 - choosing the number of topics
  "geometry",     # Chapter 17 - choosing the number of topics
  "SnowballC",    # Chapter 17 - word stemming
  "wordcloud"     # Chapter 17 - word clouds
)

## Step 3: Install any packages that are missing
new_packages <- packages[!(packages %in% installed.packages()[, "Package"])]
if (length(new_packages) > 0) {
  cat("Installing", length(new_packages), "package(s):", paste(new_packages, collapse = ", "), "\n")
  install.packages(new_packages)
} else {
  cat("All packages are already installed.\n")
}

## Step 4: Check that every package loads
results <- data.frame(package = packages, version = "", status = "", stringsAsFactors = FALSE)
for (i in seq_along(packages)) {
  loaded <- suppressWarnings(suppressPackageStartupMessages(
    requireNamespace(packages[i], quietly = TRUE)))
  if (loaded) {
    results$version[i] <- as.character(packageVersion(packages[i]))
    results$status[i] <- "OK"
  } else {
    results$status[i] <- "FAILED - try install.packages() again"
  }
}

## Step 5: Quick test that plots work (a plot should appear in the Plots pane)
library(ggplot2)
print(ggplot(data.frame(x = 1:10, y = (1:10)^2), aes(x = x, y = y)) +
        geom_line(color = "steelblue") +
        labs(title = "If you can see this plot, plotting works!") +
        theme_minimal())

## Step 6: Report
cat("\n==================== Package Report ====================\n")
print(results, row.names = FALSE)
n_failed <- sum(results$status != "OK")
if (n_failed == 0) {
  cat("\nSUCCESS: All", length(packages), "packages are installed and load correctly.",
      "\nYou are ready to run the chapter examples.\n")
} else {
  cat("\nPROBLEM:", n_failed, "package(s) did not load:",
      paste(results$package[results$status != "OK"], collapse = ", "),
      "\nTry running this script again. If a package still fails, restart R",
      "\n(Session > Restart R in RStudio) and run the script one more time.\n")
}
