## Prepare your workspace

# Load tidyverse and palmerpenguins libraries
library(tidyverse)
## Warning: package 'tidyverse' was built under R version 4.5.3
## Warning: package 'ggplot2' was built under R version 4.5.3
## Warning: package 'tibble' was built under R version 4.5.3
## Warning: package 'tidyr' was built under R version 4.5.3
## Warning: package 'readr' was built under R version 4.5.3
## Warning: package 'purrr' was built under R version 4.5.3
## Warning: package 'dplyr' was built under R version 4.5.3
## Warning: package 'stringr' was built under R version 4.5.3
## Warning: package 'lubridate' was built under R version 4.5.3
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.2.1     ✔ readr     2.2.0
## ✔ forcats   1.0.1     ✔ stringr   1.6.0
## ✔ ggplot2   4.0.4     ✔ tibble    3.3.1
## ✔ lubridate 1.9.5     ✔ tidyr     1.3.2
## ✔ purrr     1.2.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(palmerpenguins)
## Warning: package 'palmerpenguins' was built under R version 4.5.3
## 
## Attaching package: 'palmerpenguins'
## 
## The following objects are masked from 'package:datasets':
## 
##     penguins, penguins_raw
library(ggplot2)

##Prompt for a multi-variable scatter plot

# Create a ggplot scatter plot using the penguins dataset
# Plot bill_length_mm on the x-axis and bill_depth_mm on the y-axis
# Color points by species and use geom_point with size 3
# Add a minimal theme and clean labels
penguins_plot <- ggplot(penguins, aes(x = bill_length_mm, y = bill_depth_mm, color = species)) +
  geom_point(size = 3) +
  theme_minimal() +
  labs(x = "Bill Length (mm)", y = "Bill Depth (mm)", title = "Penguin Bill Dimensions")
penguins_plot
## Warning: Removed 2 rows containing missing values or values outside the scale range
## (`geom_point()`).

## Open-ended comparative plotting
#[Your turn: Write 3-4 descriptive lines here explaining your choice]
#Next, hit Enter, let Copilot predict the ggplot pipeline, and press Tab to accept

## Option A (Distribution Check)

# Create a ggplot boxplot using the penguins dataset
# Plot species on the x-axis and flipper_length
# Facet by island  and fill boxes by species using a custom palette: Adelie = orange, Chinstrap = purple, Gentoo = green
# Add a minimal theme and clear axis labels with the title "Penguin Flipper Length by Species and Island"
penguins_boxplot <- ggplot(penguins, aes(x = species, y = flipper_length_mm, fill = species)) +
  geom_boxplot() + 
  facet_wrap(~ island) +
  scale_fill_manual(values = c("Adelie" = "orange", "Chinstrap" = "purple", "Gentoo" = "green")) +
  theme_minimal() +
  labs(x = "Species", y = "Flipper Length (mm)", title = "Penguin Flipper Length by Species and Island")
penguins_boxplot
## Warning: Removed 2 rows containing non-finite outside the scale range
## (`stat_boxplot()`).

## Option B (Biomass Correlation)

# Create a ggplot scatter plot using the penguins dataset
# Plot flipper_length_mm on the x-axis and body_mass_g on the y-axis, coloring points by species
# Use geom_point with size 3 and add a separate linear regression line for each species using geom_smooth with method = "lm"
# Add a minimal theme and clear axis labels with the title "Penguin Body Mass and Flipper Length"
penguins_plot <- ggplot(penguins, aes(x = flipper_length_mm, y = body_mass_g, color = species)) +
  geom_point(size = 3) +
  geom_smooth(method = "lm", se = FALSE) +
  theme_minimal() +
  labs(x = "Flipper Length (mm)", y = "Body Mass (g)", title = "Penguin Body Mass and Flipper Length")
penguins_plot
## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 2 rows containing non-finite outside the scale range
## (`stat_smooth()`).
## Warning: Removed 2 rows containing missing values or values outside the scale range
## (`geom_point()`).

iris_data <- iris
ggplot(iris_data, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +   geom_point()

## Base R: if and else
# Simple Example: Checking Sea Surface Temperature (SSt)
sst <-30.2

if (sst > 29.5) {
  print("Warning: Marine heatwave threshold exceeded!")
} else {
  print ("SST remains within baseline parameters.")
}
## [1] "Warning: Marine heatwave threshold exceeded!"
## if_else()
# Sample coral data
coral_monitoring <- tibble(
  site = c("Site_A","Site_B", "Site_C"),
  depth_m = c(12, 35, 8)
)

# Classify depth using if_else
coral_monitoring <- coral_monitoring %>%
  mutate(zone = if_else(depth_m > 30, "Deep Reef", "Shallow Reef"))

coral_monitoring
## # A tibble: 3 × 3
##   site   depth_m zone        
##   <chr>    <dbl> <chr>       
## 1 Site_A      12 Shallow Reef
## 2 Site_B      35 Deep Reef   
## 3 Site_C       8 Shallow Reef
#Task: Finding out what mutate and >%> do
?mutate
## starting httpd help server ... done
help("%>%", package = "magrittr")

## case_when()
coral_monitoring <- coral_monitoring %>%
  mutate(reef_category = case_when(
    depth_m < 10 ~ "Lagoon / Flats",
    depth_m <= 30 ~ "Crest / Slope",
    depth_m > 30 ~ "Mesophotic / Deep",
    TRUE ~ "Unclassified" # Catch-all remainder
  ))

#Task: Environmental stress classification
marine_stations <- tibble(
  salinity = c(35, 28, 32, 12)
)

# Classify each station by salinity
marine_stations <- marine_stations %>%
  mutate(environment_type = case_when(
    salinity < 15 ~ "Estuarine",
    salinity <= 30 ~ "Brackish",
    salinity > 30 ~ "Marine",
    TRUE ~ "Unclassified"
  ))

marine_stations
## # A tibble: 4 × 2
##   salinity environment_type
##      <dbl> <chr>           
## 1       35 Marine          
## 2       28 Brackish        
## 3       32 Marine          
## 4       12 Estuarine
str(marine_stations)
## tibble [4 × 2] (S3: tbl_df/tbl/data.frame)
##  $ salinity        : num [1:4] 35 28 32 12
##  $ environment_type: chr [1:4] "Marine" "Brackish" "Marine" "Estuarine"
## Base R: for-loops
# Classic loop anatomy 
for (year in 2020:2024) {
  print(paste("Processing climate data for year:", year))
}
## [1] "Processing climate data for year: 2020"
## [1] "Processing climate data for year: 2021"
## [1] "Processing climate data for year: 2022"
## [1] "Processing climate data for year: 2023"
## [1] "Processing climate data for year: 2024"
# Loop across index seuences 
transect_lengths <-c(50, 100, 25, 75)

for(i in seq_along(transect_lengths)) {
  print(paste("Transect number", i, "measures", transect_lengths[i], "meters"))
}
## [1] "Transect number 1 measures 50 meters"
## [1] "Transect number 2 measures 100 meters"
## [1] "Transect number 3 measures 25 meters"
## [1] "Transect number 4 measures 75 meters"
## Using a standard for-loop
site_areas <- c(144, 400, 625)
results <- numeric(length(site_areas)) #Must build an empty container first

for (i in seq_along(site_areas)) {
  results[i] <- sqrt(site_areas[i])
}

## Using the purr equivalent
library(purrr)
# Map directly and define your expected output type explicitly
mapped_results <- map_dbl(site_areas, sqrt)

mapped_results
## [1] 12 20 25
# Iterate a summary function over split lists of data 
iris %>%
  split(.$Species) %>%
  map(~ summary(.x))
## $setosa
##   Sepal.Length    Sepal.Width     Petal.Length    Petal.Width   
##  Min.   :4.300   Min.   :2.300   Min.   :1.000   Min.   :0.100  
##  1st Qu.:4.800   1st Qu.:3.200   1st Qu.:1.400   1st Qu.:0.200  
##  Median :5.000   Median :3.400   Median :1.500   Median :0.200  
##  Mean   :5.006   Mean   :3.428   Mean   :1.462   Mean   :0.246  
##  3rd Qu.:5.200   3rd Qu.:3.675   3rd Qu.:1.575   3rd Qu.:0.300  
##  Max.   :5.800   Max.   :4.400   Max.   :1.900   Max.   :0.600  
##        Species  
##  setosa    :50  
##  versicolor: 0  
##  virginica : 0  
##                 
##                 
##                 
## 
## $versicolor
##   Sepal.Length    Sepal.Width     Petal.Length   Petal.Width          Species  
##  Min.   :4.900   Min.   :2.000   Min.   :3.00   Min.   :1.000   setosa    : 0  
##  1st Qu.:5.600   1st Qu.:2.525   1st Qu.:4.00   1st Qu.:1.200   versicolor:50  
##  Median :5.900   Median :2.800   Median :4.35   Median :1.300   virginica : 0  
##  Mean   :5.936   Mean   :2.770   Mean   :4.26   Mean   :1.326                  
##  3rd Qu.:6.300   3rd Qu.:3.000   3rd Qu.:4.60   3rd Qu.:1.500                  
##  Max.   :7.000   Max.   :3.400   Max.   :5.10   Max.   :1.800                  
## 
## $virginica
##   Sepal.Length    Sepal.Width     Petal.Length    Petal.Width   
##  Min.   :4.900   Min.   :2.200   Min.   :4.500   Min.   :1.400  
##  1st Qu.:6.225   1st Qu.:2.800   1st Qu.:5.100   1st Qu.:1.800  
##  Median :6.500   Median :3.000   Median :5.550   Median :2.000  
##  Mean   :6.588   Mean   :2.974   Mean   :5.552   Mean   :2.026  
##  3rd Qu.:6.900   3rd Qu.:3.175   3rd Qu.:5.875   3rd Qu.:2.300  
##  Max.   :7.900   Max.   :3.800   Max.   :6.900   Max.   :2.500  
##        Species  
##  setosa    : 0  
##  versicolor: 0  
##  virginica :50  
##                 
##                 
## 
# Task using chattr:

fish_counts <- list(
  trout = c(12, 15, 18, 14),
  salmon = c(20, 25, 22, 28),
  bass = c(8, 10, 12, 9)
)

mean_counts_loop <- numeric(length(fish_counts))

for (i in seq_along(fish_counts)) {
  mean_counts_loop[i] <- mean(fish_counts[[i]])
}

names(mean_counts_loop) <- names(fish_counts)

mean_counts_loop
##  trout salmon   bass 
##  14.75  23.75   9.75
## Function construction blueprint
# Function definition
calculate_coral_mortality <- function(initial_count, surviving_count) {
  
  # Logic safety switch using our conditional tools!
  if (initial_count <= 0) {
    stop("Initial count must be greater than zero.")
  }
  
  mortality_rate <- (initial_count - surviving_count) / initial_count
  return(mortality_rate)
}

# Utilizing your custom function
calculate_coral_mortality(initial_count = 120, surviving_count = 84)
## [1] 0.3
## Student Exercise 4: Custom Function Construction Task
# Convert Celsius to Fahrenheit
convert_temp_c_to_f <- function(temp_c) {
  
  # Reject temperatures below absolute zero
  if (temp_c < -273.15) {
    stop("Temperature cannot be below absolute zero (-273.15°C).")
  }
  
  temp_f <- (temp_c * 9 / 5) + 32
  return(temp_f)
}

convert_temp_c_to_f(25)
## [1] 77

Testing an invalid temperature

convert_temp_c_to_f(-300)
## Error in `convert_temp_c_to_f()`:
## ! Temperature cannot be below absolute zero (-273.15°C).
## Challenge 1: Nested Multi-Vector Iteration
# Raw survey counts and matching scaling factors
counts <- c(15, 24, 8, 42)
factors <- c(1.2, 0.8, 2.5, 1.1)

# Multiply each matching pair
scaled_abundance <- map2_dbl(
  counts,
  factors,
  function(count, factor) count * factor
)

# Display the result
scaled_abundance
## [1] 18.0 19.2 20.0 46.2
## Challenge 2: The Robust Data Wrangling Pipeline Function

library(dplyr)

# Define the cleaning and classification function
clean_and_classify_survey <- function(data, column_name, threshold) {
  
  # Check that the specified column exists
  if (!column_name %in% names(data)) {
    stop(
      paste0("Column '", column_name, "' was not found in the data."),
      call. = FALSE
    )
  }
  
  # Remove missing values and create the status column
  cleaned_data <- data %>%
    filter(!is.na(.data[[column_name]])) %>%
    mutate(
      status = if_else(
        .data[[column_name]] >= threshold,
        "High",
        "Low"
      )
    )
  
  return(cleaned_data)
}

# Create mock survey data with one missing value
survey_data <- tibble(
  site = c("Site_A", "Site_B", "Site_C", "Site_D"),
  fish_count = c(15, NA, 8, 42)
)

# Run the function and save its returned table
cleaned_survey <- clean_and_classify_survey(
  survey_data,
  column_name = "fish_count",
  threshold = 20
)

# Display the outcome
cleaned_survey
## # A tibble: 3 × 3
##   site   fish_count status
##   <chr>       <dbl> <chr> 
## 1 Site_A         15 Low   
## 2 Site_C          8 Low   
## 3 Site_D         42 High