Quickstart for Melanoplus Niche Modeling

Modules 1, 2, and 3 (Spatial Ecology, CART, and Random Forest)

Overview

In this lab series, you will use three interactive R Shiny applications to explore the biogeography and environmental niches of North American Melanoplus grasshoppers:

  • Module 1 (app1.R): Fundamental Niche & Environmental PCA
  • Module 2 (app2.R): Predictive Rules & Decision Trees (CART)
  • Module 3 (app3.R): Probabilities & Random Forest Ensembles

These applications process high-resolution (1 km) continental climate rasters and train 500-tree machine learning ensembles on your computer, so there are some minimum system requirements and some set up before we can begin.


1. System Requirements

Check that your computer meets the following hardware and operating system requirements:

Requirement Minimum Recommended
Operating System Windows 10/11 (64-bit), macOS 12+, or Ubuntu Linux Windows 11 or macOS 13+
Memory (RAM) 8 GB 16 GB or higher
Free Disk Space 2 GB free local storage 5 GB+ on a Solid State Drive (SSD)
Screen Resolution 1366 x 768 1920 x 1080 (Full HD)
Internet Connection Required on launch to load North American map borders Broadband / Campus Wi-Fi

Important Note on Chromebooks & Tablets: Chromebooks, iPads, and Android tablets cannot run local installations of RStudio and the C++ geospatial libraries (terra) required for these modules. If you only have access to a Chromebook or tablet, please use a campus computer lab workstation.


2. Step-by-Step Installation

Step 1: Install R and RStudio

If you do not already have R (version 4.3.0 or newer) and RStudio Desktop installed:

  1. Download and install R: Go to https://cloud.r-project.org/ and download the installer for your operating system (Windows or macOS).
    • Mac Users: Pay attention to whether your Mac has an Apple Silicon (M1/M2/M3/M4) chip or an older Intel chip, and download the matching installer.
  2. Download and install RStudio Desktop: Go to https://posit.co/download/rstudio-desktop/ and run the free RStudio installer.

Step 2: Unpack the Course Files

  1. Download the Melanoplus_Modules.zip archive from the course LMS.
  2. Extract (Unzip) the folder to a local directory on your computer, such as your Desktop or Documents folder.
    • Windows Users: Right-click the .zip file and select Extract All… Do not double-click into the .zip file and open scripts before extracting—R will not be able to find the climate rasters!
    • OneDrive / iCloud Warning: If your Desktop or Documents folder automatically backs up to OneDrive or iCloud, right-click the extracted Melanoplus_Modules folder and select “Always keep on this device” (or move it to C:/Projects/). Cloud “Files On-Demand” will block R from reading the 1 km climate raster.

Verify that your extracted folder contains the exact layout below:

Melanoplus_Modules/
├── app1.R
├── app2.R
├── app3.R
└── data/
    ├── melanoplus_aggregated.csv
    ├── Melanopulus_species.csv
    ├── bioclim_na_albers_1km.tif
    └── template_100km.tif

Step 3: Run the One-Time Package Setup Script

We will need to install some libraries to extend the base R operations. Open RStudio. Copy the entire block of code below, paste it into the Console pane (bottom-left window), and press Enter. Make sure you are connected to the internet.

# ==========================================================
# STUDENT ENVIRONMENT SETUP SCRIPT (Modules 1, 2, and 3)
# ==========================================================

# 1. Check R Version
if (getRversion() < "4.3.0") {
  warning("Your R version is older than 4.3.0. Please update R from [https://cloud.r-project.org/](https://cloud.r-project.org/) to avoid spatial package errors.")
}

# 2. Install all required packages across Modules 1, 2, and 3
required_pkgs <- c(
  "shiny",            # Interactive web application framework
  "shinycssloaders",  # Loading animations
  "dplyr",            # Data filtering and aggregation
  "tidyr",            # Missing data handling
  "terra",            # Spatial raster and Albers projection engine
  "geodata",          # North American country border polygons
  "rpart",            # Classification and Regression Trees (Module 2)
  "rpart.plot",       # Decision tree plotting (Module 2)
  "randomForest",     # 500-tree ensemble machine learning (Module 3)
  "pROC"              # ROC and AUC model evaluation (Module 3)
)

missing_pkgs <- required_pkgs[!(required_pkgs %in% installed.packages()[, "Package"])]

if (length(missing_pkgs) > 0) {
  message("Installing missing packages: ", paste(missing_pkgs, collapse = ", "))
  install.packages(missing_pkgs, dependencies = TRUE)
} else {
  message("All required packages are already installed!")
}

# 3. Verify geospatial libraries and test border download
library(terra)
library(geodata)
test_borders <- geodata::world(path = tempdir())
message("SETUP COMPLETE! Your computer is ready to run Modules 1, 2, and 3.")

Note during installation: If R asks “Do you want to install from sources the package which needs compilation? (Yes/no/cancel)”, type no and press Enter to install the faster, pre-compiled binary version.


3. How to Launch the Apps

  1. Open RStudio.
  2. Go to File -> Open File… and select app1.R (or app2.R / app3.R) inside your extracted Melanoplus_Modules folder.
  3. Set your working directory to the folder containing the script:
    • In the top RStudio menu bar, click Session -> Set Working Directory -> To Source File Location.
  4. Click the green Run App button in the top-right corner of the script editor window.
  5. Once the app window opens, click “Open in Browser” at the top of the popup window for the best full-screen layout.
  6. To switch modules: Close the browser tab and click the red Stop sign icon in the top-right corner of the RStudio Console before opening the next app.

4. Troubleshooting Common Errors

Error 1: cannot open file 'data/melanoplus_aggregated.csv': No such file or directory or [rast] file does not exist

  • Cause: Either your R working directory is not set to the Melanoplus_Modules folder, or you opened app1.R from inside an unextracted .zip file.
  • Fix:
    1. Ensure the folder is fully unzipped.
    2. In RStudio, click Session -> Set Working Directory -> To Source File Location, then click Run App again.

Error 2: App freezes or crashes when clicking “Run Forest (500 Trees)” in Module 3

  • Cause: Training 500 trees across all ~40+ species groups with high observation caps can exceed 8 GB of system RAM.
  • Fix:
    1. Close heavy background applications (especially dozens of Chrome tabs or Zoom video feeds).
    2. Keep the Max Observations per Group slider between 250 and 500.
    3. Select 2 to 5 Specific Species Groups rather than running Entire Genus with thousands of points on an 8 GB laptop.

Error 3: Error in geodata::world(path = tempdir()) on Startup

  • Cause: On initial launch, the app downloads the vector borders for Canada, the United States, and Mexico into a temporary folder. If your Wi-Fi is disconnected when you first click Run App, the download fails.
  • Fix: Connect to Wi-Fi and click Run App once. Once cached in your active R session, it will not need to re-download until you restart R.

Error 4: Plots look squished or overlap on screen

  • Cause: RStudio’s built-in preview window is often too narrow for side-by-side maps and 4x4 environmental pairs plots.
  • Fix: Click the Open in Browser button at the top of the Shiny preview window and maximize your web browser.