# Housekeeping
## Inventory every active object currently residing in session RAM
objects()
## character(0)
## Purge global environment
rm (list = ls())

# Confirm that global session memory now completely vacant
objects()
## character(0)
# Load the primary data science framework and Excel import library
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(readxl)
## Warning: package 'readxl' was built under R version 4.5.3
library(readr)

# Practice Import A: Loading a standard comma-separated plain text file
benthic_cover <- read_csv(here::here("data/workshop1/reef_cover_log.csv"))
## Rows: 6 Columns: 7
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (1): site_id
## dbl  (5): transect_no, depth_m, hard_coral_pct, macroalgae_pct, bare_substra...
## date (1): date
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# Practice Import B: Parsing a tab-separated telemetry instrument array string
acoustic_stream <- read_tsv(here::here("data/workshop1/acoustic_telemetry_stream.txt"))
## Rows: 6 Columns: 5
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: "\t"
## chr  (3): receiver_id, tag_id, species
## dbl  (1): sensor_depth_m
## dttm (1): timestamp
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# Practice Import C: Taregeting a specific sheet in a multi-tab Excel spreadsheet
fisheries_annual <- read_excel(here::here("data/workshop1/fish_catch_data.xlsx"), sheet = "Commercial_2026")

# Read in mangrove_data 
mangrove_data <- read_csv(file = here::here("data/workshop1/mangrove_survey_raw.csv"))
## Warning: One or more parsing issues, call `problems()` on your data frame for details,
## e.g.:
##   dat <- vroom(...)
##   problems(dat)
## Rows: 11 Columns: 1
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (1): Field team: Smith and Jones
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# Use args within read_csv to skip headers and declare missing flags
mangrove_data <- read_csv(
  here::here("data/workshop1/mangrove_survey_raw.csv"), 
  skip = 5, # Skip the first 5 lines of field notes
  na = c(".", "NA", "9999", "ND", "blank")) # Convert known text alts to true NA
## Rows: 6 Columns: 6
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (2): site_id, notes
## dbl (4): plot_no, canopy_height_m, crab_burrows_count, salinity_ppt
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# Force a modern tibble to degrade into a legacy base R data frame structure
benthic_cover_df <- as.data.frame(benthic_cover)

# Print the old-style dataframe structure to view
print(benthic_cover_df)
##        site_id transect_no       date depth_m hard_coral_pct macroalgae_pct
## 1    Nelly_Bay           1 2026-05-10     4.5           45.2           12.1
## 2    Nelly_Bay           2 2026-05-10     5.1           38.5           15.4
## 3 Geoffrey_Bay           1 2026-05-11     3.8           52.1            8.3
## 4 Geoffrey_Bay           2 2026-05-11     4.2           48.9           10.2
## 5 Florence_Bay           1 2026-05-12     6.0           61.3            5.1
## 6 Florence_Bay           2 2026-05-12     5.8           58.7            6.4
##   bare_substrate_pct
## 1               42.7
## 2               46.1
## 3               39.6
## 4               40.9
## 5               33.6
## 6               34.9
# And compare with tibble alternative
print(benthic_cover)
## # A tibble: 6 × 7
##   site_id      transect_no date       depth_m hard_coral_pct macroalgae_pct
##   <chr>              <dbl> <date>       <dbl>          <dbl>          <dbl>
## 1 Nelly_Bay              1 2026-05-10     4.5           45.2           12.1
## 2 Nelly_Bay              2 2026-05-10     5.1           38.5           15.4
## 3 Geoffrey_Bay           1 2026-05-11     3.8           52.1            8.3
## 4 Geoffrey_Bay           2 2026-05-11     4.2           48.9           10.2
## 5 Florence_Bay           1 2026-05-12     6             61.3            5.1
## 6 Florence_Bay           2 2026-05-12     5.8           58.7            6.4
## # ℹ 1 more variable: bare_substrate_pct <dbl>
# Load the package data into active memory 
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
data("penguins")

# Examine the structure of the dataset - always do this when loading a new dataset!
glimpse(penguins) #tidyverse version (from dplyr package)
## Rows: 344
## Columns: 8
## $ species           <fct> Adelie, Adelie, Adelie, Adelie, Adelie, Adelie, Adel…
## $ island            <fct> Torgersen, Torgersen, Torgersen, Torgersen, Torgerse…
## $ bill_length_mm    <dbl> 39.1, 39.5, 40.3, NA, 36.7, 39.3, 38.9, 39.2, 34.1, …
## $ bill_depth_mm     <dbl> 18.7, 17.4, 18.0, NA, 19.3, 20.6, 17.8, 19.6, 18.1, …
## $ flipper_length_mm <int> 181, 186, 195, NA, 193, 190, 181, 195, 193, 190, 186…
## $ body_mass_g       <int> 3750, 3800, 3250, NA, 3450, 3650, 3625, 4675, 3475, …
## $ sex               <fct> male, female, female, NA, female, male, female, male…
## $ year              <int> 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007…
str(penguins) #base R version
## tibble [344 × 8] (S3: tbl_df/tbl/data.frame)
##  $ species          : Factor w/ 3 levels "Adelie","Chinstrap",..: 1 1 1 1 1 1 1 1 1 1 ...
##  $ island           : Factor w/ 3 levels "Biscoe","Dream",..: 3 3 3 3 3 3 3 3 3 3 ...
##  $ bill_length_mm   : num [1:344] 39.1 39.5 40.3 NA 36.7 39.3 38.9 39.2 34.1 42 ...
##  $ bill_depth_mm    : num [1:344] 18.7 17.4 18 NA 19.3 20.6 17.8 19.6 18.1 20.2 ...
##  $ flipper_length_mm: int [1:344] 181 186 195 NA 193 190 181 195 193 190 ...
##  $ body_mass_g      : int [1:344] 3750 3800 3250 NA 3450 3650 3625 4675 3475 4250 ...
##  $ sex              : Factor w/ 2 levels "female","male": 2 1 1 NA 1 2 1 2 NA NA ...
##  $ year             : int [1:344] 2007 2007 2007 2007 2007 2007 2007 2007 2007 2007 ...
# Generate an exploratory summary matrix
summary(penguins)
##       species          island    bill_length_mm  bill_depth_mm  
##  Adelie   :152   Biscoe   :168   Min.   :32.10   Min.   :13.10  
##  Chinstrap: 68   Dream    :124   1st Qu.:39.23   1st Qu.:15.60  
##  Gentoo   :124   Torgersen: 52   Median :44.45   Median :17.30  
##                                  Mean   :43.92   Mean   :17.15  
##                                  3rd Qu.:48.50   3rd Qu.:18.70  
##                                  Max.   :59.60   Max.   :21.50  
##                                  NA's   :2       NA's   :2      
##  flipper_length_mm  body_mass_g       sex           year     
##  Min.   :172.0     Min.   :2700   female:165   Min.   :2007  
##  1st Qu.:190.0     1st Qu.:3550   male  :168   1st Qu.:2007  
##  Median :197.0     Median :4050   NA's  : 11   Median :2008  
##  Mean   :200.9     Mean   :4202                Mean   :2008  
##  3rd Qu.:213.0     3rd Qu.:4750                3rd Qu.:2009  
##  Max.   :231.0     Max.   :6300                Max.   :2009  
##  NA's   :2         NA's   :2
# Vertically slice specific morphometric variables by explicit name
morphology_metrics <- select(penguins, species, bill_length_mm, bill_depth_mm, body_mass_g)
glimpse (morphology_metrics)
## Rows: 344
## Columns: 4
## $ species        <fct> Adelie, Adelie, Adelie, Adelie, Adelie, Adelie, Adelie,…
## $ bill_length_mm <dbl> 39.1, 39.5, 40.3, NA, 36.7, 39.3, 38.9, 39.2, 34.1, 42.…
## $ bill_depth_mm  <dbl> 18.7, 17.4, 18.0, NA, 19.3, 20.6, 17.8, 19.6, 18.1, 20.…
## $ body_mass_g    <int> 3750, 3800, 3250, NA, 3450, 3650, 3625, 4675, 3475, 425…
# Retain a continuous block of attributes using the colon operator
spatial_block <- select(penguins, species:island)

# Discard logistics tracking attributes while preserving everything else using the minus sign
clean_scientific_fields <- select(penguins, -year)

# Isolate observations belonging to a single categorical target group 
adelie_cohort <- filter(penguins, species == "Adelie")

# Sift out individuals using continous numerical boundary thresholds 
# Preserves only large penguins whose mass exceeds 4500 grams
heavy_penguins <- filter(penguins, body_mass_g > 4500)

# Combine multiple conditional parameters across separate attributes
# Preserves records matching Gentoo penguins sampled explicitly on Biscoe Island
biscoe_gentoos <- filter(penguins, species == "Gentoo" & island == "Biscoe")

# Sift records matching multiple targeting flags within an explicit set 
sub_islands <- filter(penguins, island %in% c("Dream", "Torgersen"))

# Sort penguins by ascending body mass (Default setting: Smallest mass first)
lightest_first <- arrange(penguins, body_mass_g)

# Sort penguins in descending sequence using the desc () layout wrapper
heaviest_first <- arrange(penguins, desc(body_mass_g))

# Execute nested sorting criteria: Group by species, then sort by descending bill length
stratified_morphology <- arrange(penguins, species, desc(bill_length_mm))

penguins_final <- penguins |>
  mutate(bill_ratio = bill_length_mm / bill_depth_mm) |>
  filter(species == "Adelie")

# Calculate a new morphological ratio in our environment
penguin_ratios <- penguins |>
  mutate(body_mass_kg = body_mass_g / 1000, # Convert grams to kilograms
         bill_ratio = bill_length_mm / bill_depth_mm # Bill ratio
  )

# View your newly engineered variables appended to the far-right columns
glimpse(penguin_ratios)
## Rows: 344
## Columns: 10
## $ species           <fct> Adelie, Adelie, Adelie, Adelie, Adelie, Adelie, Adel…
## $ island            <fct> Torgersen, Torgersen, Torgersen, Torgersen, Torgerse…
## $ bill_length_mm    <dbl> 39.1, 39.5, 40.3, NA, 36.7, 39.3, 38.9, 39.2, 34.1, …
## $ bill_depth_mm     <dbl> 18.7, 17.4, 18.0, NA, 19.3, 20.6, 17.8, 19.6, 18.1, …
## $ flipper_length_mm <int> 181, 186, 195, NA, 193, 190, 181, 195, 193, 190, 186…
## $ body_mass_g       <int> 3750, 3800, 3250, NA, 3450, 3650, 3625, 4675, 3475, …
## $ sex               <fct> male, female, female, NA, female, male, female, male…
## $ year              <int> 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007…
## $ body_mass_kg      <dbl> 3.750, 3.800, 3.250, NA, 3.450, 3.650, 3.625, 4.675,…
## $ bill_ratio        <dbl> 2.090909, 2.270115, 2.238889, NA, 1.901554, 1.907767…
# Grouping our active memory penguins by species
grouped_penguins <- group_by(penguins, species)

# Notice that the table looks identical, but metadata notes 'Groups: species [3]'
print(grouped_penguins)
## # A tibble: 344 × 8
## # Groups:   species [3]
##    species island    bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
##    <fct>   <fct>              <dbl>         <dbl>             <int>       <int>
##  1 Adelie  Torgersen           39.1          18.7               181        3750
##  2 Adelie  Torgersen           39.5          17.4               186        3800
##  3 Adelie  Torgersen           40.3          18                 195        3250
##  4 Adelie  Torgersen           NA            NA                  NA          NA
##  5 Adelie  Torgersen           36.7          19.3               193        3450
##  6 Adelie  Torgersen           39.3          20.6               190        3650
##  7 Adelie  Torgersen           38.9          17.8               181        3625
##  8 Adelie  Torgersen           39.2          19.6               195        4675
##  9 Adelie  Torgersen           34.1          18.1               193        3475
## 10 Adelie  Torgersen           42            20.2               190        4250
## # ℹ 334 more rows
## # ℹ 2 more variables: sex <fct>, year <int>
# Collapsing the buckets into explicit summary metrics
species_mass_summary <- summarise (grouped_penguins,
  mean_mass_g = mean(body_mass_g)
)

print(species_mass_summary)
## # A tibble: 3 × 2
##   species   mean_mass_g
##   <fct>           <dbl>
## 1 Adelie            NA 
## 2 Chinstrap       3733.
## 3 Gentoo            NA
# Overcoming the missing value trap using na.rm = TRUE
biological_signal <- penguins %>%
  group_by(species, sex) %>%
  summarise(
    sample_size = n(),                                     # Count total individuals per category
    mean_mass_g = mean(body_mass_g, na.rm = TRUE),         # Calculate mean ignoring missing cells
    sd_mass_g   = sd(body_mass_g, na.rm = TRUE)            # Standard deviation calculation
  )
## `summarise()` has regrouped the output.
## ℹ Summaries were computed grouped by species and sex.
## ℹ Output is grouped by species.
## ℹ Use `summarise(.groups = "drop_last")` to silence this message.
## ℹ Use `summarise(.by = c(species, sex))` for per-operation grouping
##   (`?dplyr::dplyr_by`) instead.
print (biological_signal)
## # A tibble: 8 × 5
## # Groups:   species [3]
##   species   sex    sample_size mean_mass_g sd_mass_g
##   <fct>     <fct>        <int>       <dbl>     <dbl>
## 1 Adelie    female          73       3369.      269.
## 2 Adelie    male            73       4043.      347.
## 3 Adelie    <NA>             6       3540       477.
## 4 Chinstrap female          34       3527.      285.
## 5 Chinstrap male            34       3939.      362.
## 6 Gentoo    female          58       4680.      282.
## 7 Gentoo    male            61       5485.      313.
## 8 Gentoo    <NA>             5       4588.      338.
## Example: Visualizing mean trends with uncertainty 

# Pipe directly from aggregation to plotting with error bars
mass_compare_plot <- penguins |>
  group_by(species, island) |>
  summarise(
    mean_mass = mean(body_mass_g, na.rm = TRUE),
    sd_mass   = sd(body_mass_g, na.rm = TRUE),
    n = n(),
    .groups = "drop"
  ) |>
  ggplot(aes(x = species, y = mean_mass, colour = island)) +
  geom_point(size = 3) +
  geom_errorbar(aes(ymin = mean_mass - sd_mass, 
                    ymax = mean_mass + sd_mass), 
                width = 0.2) +
  labs(title = "Mean Body Mass by Species and Island",
       subtitle = "Error bars represent standard deviation",
       y = "Mean Body Mass (g)",
       x = "Species") +
  theme_minimal()

mass_compare_plot  

# Create output directories if they do not exist:
if(!dir.exists("outputs/figures")) dir.create("outputs/figures") # folder for figs
## Warning in dir.create("outputs/figures"): cannot create dir 'outputs\figures',
## reason 'No such file or directory'
if(!dir.exists("outputs/tables")) dir.create("outputs/tables") # folder for tables
## Warning in dir.create("outputs/tables"): cannot create dir 'outputs\tables',
## reason 'No such file or directory'
if(!dir.exists("Rdata")) dir.create("Rdata") # folder for Rdata objects

# 1. Exporting our collapsed summary table as a universal flat text file
readr::write_csv(
  biological_signal,
  here::here("outputs", "penguin_species_mass_summary.csv")
)

#2. Saving as a native R binary file
saveRDS(
  biological_signal,
  here::here("outputs", "penguin_species_mass_summary.rds")
)

ggplot2::ggsave(
  filename = here::here("outputs", "mass_compare_plot.png"),
  plot = mass_compare_plot,
  width = 120,
  height = 120,
  units = "mm",
  dpi = 300
)

mass_summary <- penguins %>%
  filter(!is.na(body_mass_g)) %>%
  group_by(species, island) %>%
  summarise(
    n = n(),
    mean_mass = mean(body_mass_g),
    sd_mass = sd(body_mass_g),
    .groups = "drop"
  ) %>%
  mutate(se_mass = sd_mass / sqrt(n))

mass_summary
## # A tibble: 5 × 6
##   species   island        n mean_mass sd_mass se_mass
##   <fct>     <fct>     <int>     <dbl>   <dbl>   <dbl>
## 1 Adelie    Biscoe       44     3710.    488.    73.5
## 2 Adelie    Dream        56     3688.    455.    60.8
## 3 Adelie    Torgersen    51     3706.    445.    62.3
## 4 Chinstrap Dream        68     3733.    384.    46.6
## 5 Gentoo    Biscoe      123     5076.    504.    45.5
ggplot(
  mass_summary,
  aes(x = species, y = mean_mass, colour = island)
) +
  geom_point(position = position_dodge(0.4), size = 3) +
  geom_errorbar(
    aes(
      ymin = mean_mass - sd_mass,
      ymax = mean_mass + sd_mass
    ),
    position = position_dodge(0.4),
    width = 0.15
  ) +
  labs(
    x = "Species",
    y = "Mean body mass (g)",
    colour = "Island",
    subtitle = "Error bars: ±1 standard deviation"
  ) +
  theme_minimal()

ggplot(
  mass_summary,
  aes(x = species, y = mean_mass, colour = island)
) +
  geom_point(position = position_dodge(0.4), size = 3) +
  geom_errorbar(
    aes(
      ymin = mean_mass - se_mass,
      ymax = mean_mass + se_mass
    ),
    position = position_dodge(0.4),
    width = 0.15
  ) +
  labs(
    x = "Species",
    y = "Mean body mass (g)",
    colour = "Island",
    subtitle = "Error bars: ±1 standard error"
  ) +
  theme_minimal()