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
billboard
## # A tibble: 317 × 79
##    artist     track date.entered   wk1   wk2   wk3   wk4   wk5   wk6   wk7   wk8
##    <chr>      <chr> <date>       <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
##  1 2 Pac      Baby… 2000-02-26      87    82    72    77    87    94    99    NA
##  2 2Ge+her    The … 2000-09-02      91    87    92    NA    NA    NA    NA    NA
##  3 3 Doors D… Kryp… 2000-04-08      81    70    68    67    66    57    54    53
##  4 3 Doors D… Loser 2000-10-21      76    76    72    69    67    65    55    59
##  5 504 Boyz   Wobb… 2000-04-15      57    34    25    17    17    31    36    49
##  6 98^0       Give… 2000-08-19      51    39    34    26    26    19     2     2
##  7 A*Teens    Danc… 2000-07-08      97    97    96    95   100    NA    NA    NA
##  8 Aaliyah    I Do… 2000-01-29      84    62    51    41    38    35    35    38
##  9 Aaliyah    Try … 2000-03-18      59    53    38    28    21    18    16    14
## 10 Adams, Yo… Open… 2000-08-26      76    76    74    69    68    67    61    58
## # ℹ 307 more rows
## # ℹ 68 more variables: wk9 <dbl>, wk10 <dbl>, wk11 <dbl>, wk12 <dbl>,
## #   wk13 <dbl>, wk14 <dbl>, wk15 <dbl>, wk16 <dbl>, wk17 <dbl>, wk18 <dbl>,
## #   wk19 <dbl>, wk20 <dbl>, wk21 <dbl>, wk22 <dbl>, wk23 <dbl>, wk24 <dbl>,
## #   wk25 <dbl>, wk26 <dbl>, wk27 <dbl>, wk28 <dbl>, wk29 <dbl>, wk30 <dbl>,
## #   wk31 <dbl>, wk32 <dbl>, wk33 <dbl>, wk34 <dbl>, wk35 <dbl>, wk36 <dbl>,
## #   wk37 <dbl>, wk38 <dbl>, wk39 <dbl>, wk40 <dbl>, wk41 <dbl>, wk42 <dbl>, …
billboard |>
  pivot_longer(cols = starts_with("wk"),
               names_to = "week",
               values_to = "rank"
  )
## # A tibble: 24,092 × 5
##    artist track                   date.entered week   rank
##    <chr>  <chr>                   <date>       <chr> <dbl>
##  1 2 Pac  Baby Don't Cry (Keep... 2000-02-26   wk1      87
##  2 2 Pac  Baby Don't Cry (Keep... 2000-02-26   wk2      82
##  3 2 Pac  Baby Don't Cry (Keep... 2000-02-26   wk3      72
##  4 2 Pac  Baby Don't Cry (Keep... 2000-02-26   wk4      77
##  5 2 Pac  Baby Don't Cry (Keep... 2000-02-26   wk5      87
##  6 2 Pac  Baby Don't Cry (Keep... 2000-02-26   wk6      94
##  7 2 Pac  Baby Don't Cry (Keep... 2000-02-26   wk7      99
##  8 2 Pac  Baby Don't Cry (Keep... 2000-02-26   wk8      NA
##  9 2 Pac  Baby Don't Cry (Keep... 2000-02-26   wk9      NA
## 10 2 Pac  Baby Don't Cry (Keep... 2000-02-26   wk10     NA
## # ℹ 24,082 more rows
billboard |>
  pivot_longer(cols = starts_with("wk"),
               names_to = "week",
               values_to = "rank", 
               values_drop_na = TRUE
  )
## # A tibble: 5,307 × 5
##    artist  track                   date.entered week   rank
##    <chr>   <chr>                   <date>       <chr> <dbl>
##  1 2 Pac   Baby Don't Cry (Keep... 2000-02-26   wk1      87
##  2 2 Pac   Baby Don't Cry (Keep... 2000-02-26   wk2      82
##  3 2 Pac   Baby Don't Cry (Keep... 2000-02-26   wk3      72
##  4 2 Pac   Baby Don't Cry (Keep... 2000-02-26   wk4      77
##  5 2 Pac   Baby Don't Cry (Keep... 2000-02-26   wk5      87
##  6 2 Pac   Baby Don't Cry (Keep... 2000-02-26   wk6      94
##  7 2 Pac   Baby Don't Cry (Keep... 2000-02-26   wk7      99
##  8 2Ge+her The Hardest Part Of ... 2000-09-02   wk1      91
##  9 2Ge+her The Hardest Part Of ... 2000-09-02   wk2      87
## 10 2Ge+her The Hardest Part Of ... 2000-09-02   wk3      92
## # ℹ 5,297 more rows
df <- tribble(
  ~id,  ~bp1, ~bp2,
  "A",  100,  120,
  "B",  140,  115,
  "C",  120,  125
)

df |> 
  pivot_longer(
    cols = bp1:bp2,
    names_to = "measurement",
    values_to = "value"
  )
## # A tibble: 6 × 3
##   id    measurement value
##   <chr> <chr>       <dbl>
## 1 A     bp1           100
## 2 A     bp2           120
## 3 B     bp1           140
## 4 B     bp2           115
## 5 C     bp1           120
## 6 C     bp2           125
cms_patient_experience
## # A tibble: 500 × 5
##    org_pac_id org_nm                           measure_cd measure_title prf_rate
##    <chr>      <chr>                            <chr>      <chr>            <dbl>
##  1 0446157747 USC CARE MEDICAL GROUP INC       CAHPS_GRP… CAHPS for MI…       63
##  2 0446157747 USC CARE MEDICAL GROUP INC       CAHPS_GRP… CAHPS for MI…       87
##  3 0446157747 USC CARE MEDICAL GROUP INC       CAHPS_GRP… CAHPS for MI…       86
##  4 0446157747 USC CARE MEDICAL GROUP INC       CAHPS_GRP… CAHPS for MI…       57
##  5 0446157747 USC CARE MEDICAL GROUP INC       CAHPS_GRP… CAHPS for MI…       85
##  6 0446157747 USC CARE MEDICAL GROUP INC       CAHPS_GRP… CAHPS for MI…       24
##  7 0446162697 ASSOCIATION OF UNIVERSITY PHYSI… CAHPS_GRP… CAHPS for MI…       59
##  8 0446162697 ASSOCIATION OF UNIVERSITY PHYSI… CAHPS_GRP… CAHPS for MI…       85
##  9 0446162697 ASSOCIATION OF UNIVERSITY PHYSI… CAHPS_GRP… CAHPS for MI…       83
## 10 0446162697 ASSOCIATION OF UNIVERSITY PHYSI… CAHPS_GRP… CAHPS for MI…       63
## # ℹ 490 more rows
cms_patient_experience |> 
  distinct(measure_cd, measure_title)
## # A tibble: 6 × 2
##   measure_cd   measure_title                                                    
##   <chr>        <chr>                                                            
## 1 CAHPS_GRP_1  CAHPS for MIPS SSM: Getting Timely Care, Appointments, and Infor…
## 2 CAHPS_GRP_2  CAHPS for MIPS SSM: How Well Providers Communicate               
## 3 CAHPS_GRP_3  CAHPS for MIPS SSM: Patient's Rating of Provider                 
## 4 CAHPS_GRP_5  CAHPS for MIPS SSM: Health Promotion and Education               
## 5 CAHPS_GRP_8  CAHPS for MIPS SSM: Courteous and Helpful Office Staff           
## 6 CAHPS_GRP_12 CAHPS for MIPS SSM: Stewardship of Patient Resources
cms_patient_experience |> 
  pivot_wider(
    names_from = measure_cd,
    values_from = prf_rate
  )
## # A tibble: 500 × 9
##    org_pac_id org_nm           measure_title CAHPS_GRP_1 CAHPS_GRP_2 CAHPS_GRP_3
##    <chr>      <chr>            <chr>               <dbl>       <dbl>       <dbl>
##  1 0446157747 USC CARE MEDICA… CAHPS for MI…          63          NA          NA
##  2 0446157747 USC CARE MEDICA… CAHPS for MI…          NA          87          NA
##  3 0446157747 USC CARE MEDICA… CAHPS for MI…          NA          NA          86
##  4 0446157747 USC CARE MEDICA… CAHPS for MI…          NA          NA          NA
##  5 0446157747 USC CARE MEDICA… CAHPS for MI…          NA          NA          NA
##  6 0446157747 USC CARE MEDICA… CAHPS for MI…          NA          NA          NA
##  7 0446162697 ASSOCIATION OF … CAHPS for MI…          59          NA          NA
##  8 0446162697 ASSOCIATION OF … CAHPS for MI…          NA          85          NA
##  9 0446162697 ASSOCIATION OF … CAHPS for MI…          NA          NA          83
## 10 0446162697 ASSOCIATION OF … CAHPS for MI…          NA          NA          NA
## # ℹ 490 more rows
## # ℹ 3 more variables: CAHPS_GRP_5 <dbl>, CAHPS_GRP_8 <dbl>, CAHPS_GRP_12 <dbl>
cms_patient_experience |> 
  pivot_wider(
    id_cols = starts_with("org"),
    names_from = measure_cd,
    values_from = prf_rate
  )
## # A tibble: 95 × 8
##    org_pac_id org_nm CAHPS_GRP_1 CAHPS_GRP_2 CAHPS_GRP_3 CAHPS_GRP_5 CAHPS_GRP_8
##    <chr>      <chr>        <dbl>       <dbl>       <dbl>       <dbl>       <dbl>
##  1 0446157747 USC C…          63          87          86          57          85
##  2 0446162697 ASSOC…          59          85          83          63          88
##  3 0547164295 BEAVE…          49          NA          75          44          73
##  4 0749333730 CAPE …          67          84          85          65          82
##  5 0840104360 ALLIA…          66          87          87          64          87
##  6 0840109864 REX H…          73          87          84          67          91
##  7 0840513552 SCL H…          58          83          76          58          78
##  8 0941545784 GRITM…          46          86          81          54          NA
##  9 1052612785 COMMU…          65          84          80          58          87
## 10 1254237779 OUR L…          61          NA          NA          65          NA
## # ℹ 85 more rows
## # ℹ 1 more variable: CAHPS_GRP_12 <dbl>
df <- tribble(
  ~id, ~measurement, ~value,
  "A",        "bp1",    100,
  "B",        "bp1",    140,
  "B",        "bp2",    115, 
  "A",        "bp2",    120,
  "A",        "bp3",    105
)

df |> 
  pivot_wider(
    names_from = measurement,
    values_from = value
  )
## # A tibble: 2 × 4
##   id      bp1   bp2   bp3
##   <chr> <dbl> <dbl> <dbl>
## 1 A       100   120   105
## 2 B       140   115    NA
df |> 
  distinct(measurement) |> 
  pull()
## [1] "bp1" "bp2" "bp3"
df |> 
  select(-measurement, -value) |> 
  distinct()
## # A tibble: 2 × 1
##   id   
##   <chr>
## 1 A    
## 2 B
df |> 
  select(-measurement, -value) |> 
  distinct() |> 
  mutate(x = NA, y = NA, z = NA)
## # A tibble: 2 × 4
##   id    x     y     z    
##   <chr> <lgl> <lgl> <lgl>
## 1 A     NA    NA    NA   
## 2 B     NA    NA    NA
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
# Create a long version of the penguins dataset
penguins_long <- penguins |>
  pivot_longer(
    cols = c(bill_length_mm, bill_depth_mm, flipper_length_mm, body_mass_g),
    names_to = "measurement_type",
    values_to = "value"
  )

# View the result
head(penguins_long)
## # A tibble: 6 × 6
##   species island    sex     year measurement_type   value
##   <fct>   <fct>     <fct>  <int> <chr>              <dbl>
## 1 Adelie  Torgersen male    2007 bill_length_mm      39.1
## 2 Adelie  Torgersen male    2007 bill_depth_mm       18.7
## 3 Adelie  Torgersen male    2007 flipper_length_mm  181  
## 4 Adelie  Torgersen male    2007 body_mass_g       3750  
## 5 Adelie  Torgersen female  2007 bill_length_mm      39.5
## 6 Adelie  Torgersen female  2007 bill_depth_mm       17.4
penguins_long |>
  drop_na(value) |>
  ggplot(aes(x = value, fill = species)) +
  geom_histogram(bins = 30, alpha = 0.7, colour = "black") +
  facet_wrap(~ measurement_type, scales = "free_x") +
  theme_minimal() +
  labs(
    title = "Morphometric distributions across penguin species",
    x = "Measurement value",
    y = "Frequency"
  )

mass_summary <- penguins |>
  drop_na(body_mass_g) |>
  group_by(species, island) |>
  summarise(mean_mass = mean(body_mass_g))
## `summarise()` has regrouped the output.
## ℹ Summaries were computed grouped by species and island.
## ℹ Output is grouped by species.
## ℹ Use `summarise(.groups = "drop_last")` to silence this message.
## ℹ Use `summarise(.by = c(species, island))` for per-operation grouping
##   (`?dplyr::dplyr_by`) instead.
head(mass_summary)
## # A tibble: 5 × 3
## # Groups:   species [3]
##   species   island    mean_mass
##   <fct>     <fct>         <dbl>
## 1 Adelie    Biscoe        3710.
## 2 Adelie    Dream         3688.
## 3 Adelie    Torgersen     3706.
## 4 Chinstrap Dream         3733.
## 5 Gentoo    Biscoe        5076.
mass_matrix <- mass_summary |>
  pivot_wider(
    names_from = island,
    values_from = mean_mass
  )

head(mass_matrix)
## # A tibble: 3 × 4
## # Groups:   species [3]
##   species   Biscoe Dream Torgersen
##   <fct>      <dbl> <dbl>     <dbl>
## 1 Adelie     3710. 3688.     3706.
## 2 Chinstrap    NA  3733.       NA 
## 3 Gentoo     5076.   NA        NA
table3
## # A tibble: 6 × 3
##   country      year rate             
##   <chr>       <dbl> <chr>            
## 1 Afghanistan  1999 745/19987071     
## 2 Afghanistan  2000 2666/20595360    
## 3 Brazil       1999 37737/172006362  
## 4 Brazil       2000 80488/174504898  
## 5 China        1999 212258/1272915272
## 6 China        2000 213766/1280428583
table3 %>% 
  separate(rate, into = c("cases", "population"), sep = "/")
## # A tibble: 6 × 4
##   country      year cases  population
##   <chr>       <dbl> <chr>  <chr>     
## 1 Afghanistan  1999 745    19987071  
## 2 Afghanistan  2000 2666   20595360  
## 3 Brazil       1999 37737  172006362 
## 4 Brazil       2000 80488  174504898 
## 5 China        1999 212258 1272915272
## 6 China        2000 213766 1280428583
table3 %>% 
  separate(rate, into = c("cases", "population"), convert = TRUE)
## # A tibble: 6 × 4
##   country      year  cases population
##   <chr>       <dbl>  <int>      <int>
## 1 Afghanistan  1999    745   19987071
## 2 Afghanistan  2000   2666   20595360
## 3 Brazil       1999  37737  172006362
## 4 Brazil       2000  80488  174504898
## 5 China        1999 212258 1272915272
## 6 China        2000 213766 1280428583
table3 %>% 
  separate(year, into = c("century", "year"), sep = 2)
## # A tibble: 6 × 4
##   country     century year  rate             
##   <chr>       <chr>   <chr> <chr>            
## 1 Afghanistan 19      99    745/19987071     
## 2 Afghanistan 20      00    2666/20595360    
## 3 Brazil      19      99    37737/172006362  
## 4 Brazil      20      00    80488/174504898  
## 5 China       19      99    212258/1272915272
## 6 China       20      00    213766/1280428583
table5 %>% 
  unite(new, century, year, sep = "")
## # A tibble: 6 × 3
##   country     new   rate             
##   <chr>       <chr> <chr>            
## 1 Afghanistan 1999  745/19987071     
## 2 Afghanistan 2000  2666/20595360    
## 3 Brazil      1999  37737/172006362  
## 4 Brazil      2000  80488/174504898  
## 5 China       1999  212258/1272915272
## 6 China       2000  213766/1280428583
library(tidyverse)

# A remarkably messy data frame of field sites
messy_sites <- tibble(
  site_id = c(" Nelly Bay", "nelly_bay", "NELLY BAY", " Geoffrey_Bay ", "geoffrey bay")
)

# Using stringr within mutate to standardize the text
clean_sites <- messy_sites |>
  mutate(
    # 1. Convert everything to lowercase
    site_clean = str_to_lower(site_id),
    # 2. Replace any spaces with underscores
    site_clean = str_replace_all(site_clean, pattern = " ", replacement = "_"),
    # 3. Trim any leading or trailing whitespace (invisible spaces at the ends)
    site_clean = str_trim(site_clean)
  )

print(clean_sites)
## # A tibble: 5 × 2
##   site_id          site_clean    
##   <chr>            <chr>         
## 1 " Nelly Bay"     _nelly_bay    
## 2 "nelly_bay"      nelly_bay     
## 3 "NELLY BAY"      nelly_bay     
## 4 " Geoffrey_Bay " _geoffrey_bay_
## 5 "geoffrey bay"   geoffrey_bay
library(lubridate)

# Parsing different date formats
date_1 <- dmy("25/12/2026")
date_2 <- ymd("2026-12-25")

# R now recognizes these as identical Date objects
date_1 == date_2
## [1] TRUE
# A tibble of raw sensor data with a messy character timestamp
sensor_data <- tibble(
  raw_time = c("14-05-2026 08:30:00", "14-05-2026 08:45:00", "14-05-2026 09:00:00"),
  temperature = c(24.5, 24.6, 24.4)
)

# Converting character strings to true POSIXct datetime objects
sensor_clean <- sensor_data |>
  mutate(
    true_time = dmy_hms(raw_time)
  )

print(sensor_clean)
## # A tibble: 3 × 3
##   raw_time            temperature true_time          
##   <chr>                     <dbl> <dttm>             
## 1 14-05-2026 08:30:00        24.5 2026-05-14 08:30:00
## 2 14-05-2026 08:45:00        24.6 2026-05-14 08:45:00
## 3 14-05-2026 09:00:00        24.4 2026-05-14 09:00:00
# Table 1: Biological observation data
observations <- tibble(
  site_code = c("NB", "GB", "MI", "NB", "HB"),
  species = c("Trout", "Snapper", "Trout", "Cod", "Trout"),
  count = c(5, 2, 1, 3, 8)
)

# Table 2: Spatial metadata
site_metadata <- tibble(
  site_code = c("NB", "GB", "MI", "RP", "WP"),
  zone = c("Marine National Park", "Conservation Park", "Habitat Protection", "General Use", "Other Use"),
  lat = c(-19.16, -19.15, -19.14, -19.12, -19.11)
)

# Joining metadata to our observations
joined_data <- observations |>
  left_join(site_metadata, by = join_by(site_code))

print(joined_data)
## # A tibble: 5 × 5
##   site_code species count zone                   lat
##   <chr>     <chr>   <dbl> <chr>                <dbl>
## 1 NB        Trout       5 Marine National Park -19.2
## 2 GB        Snapper     2 Conservation Park    -19.2
## 3 MI        Trout       1 Habitat Protection   -19.1
## 4 NB        Cod         3 Marine National Park -19.2
## 5 HB        Trout       8 <NA>                  NA
matched_data <- observations |>
  inner_join(site_metadata, by = join_by(site_code))

glimpse(matched_data)
## Rows: 4
## Columns: 5
## $ site_code <chr> "NB", "GB", "MI", "NB"
## $ species   <chr> "Trout", "Snapper", "Trout", "Cod"
## $ count     <dbl> 5, 2, 1, 3
## $ zone      <chr> "Marine National Park", "Conservation Park", "Habitat Protec…
## $ lat       <dbl> -19.16, -19.15, -19.14, -19.16
# Which observations are missing from our metadata dictionary?
missing_context <- observations |>
  anti_join(site_metadata, by = join_by(site_code))

# Raw data from an old temperature logger
logger_data <- tibble(
  depth_m = c(10, 20, 30, 40),
  temp_c = c(24.5, 24.1, -999, 23.5)) # -999 is a known sensor error code

# Convert the -999 error codes to true NA values
fixed_logger <- logger_data |>
  mutate(temp_c = na_if(temp_c, -999))

print(fixed_logger)
## # A tibble: 4 × 2
##   depth_m temp_c
##     <dbl>  <dbl>
## 1      10   24.5
## 2      20   24.1
## 3      30   NA  
## 4      40   23.5
# Simulate some count data
shark_counts <- tibble(
  site = c("Reef_A", "Reef_B", "Reef_C"),
  shark_count = c(3, NA, 5)) # The NA here actually means 0 sharks were seen

# Replace NA with 0
shark_fixed <- shark_counts |>
  mutate(shark_count = coalesce(shark_count, 0))

print(shark_fixed)
## # A tibble: 3 × 2
##   site   shark_count
##   <chr>        <dbl>
## 1 Reef_A           3
## 2 Reef_B           0
## 3 Reef_C           5
cpue_data <- tibble(
  site = c("Bay_1", "Bay_2"),
  catch = c(10, 0),
  effort_hours = c(2, 0))

# Calculating CPUE (catch / effort)
cpue_calc <- cpue_data |>
  mutate(
    cpue = catch / effort_hours)

print(cpue_calc)
## # A tibble: 2 × 4
##   site  catch effort_hours  cpue
##   <chr> <dbl>        <dbl> <dbl>
## 1 Bay_1    10            2     5
## 2 Bay_2     0            0   NaN
raw_catch <- tibble(
  site = c("Reef_1", "Reef_1", "Reef_2"),
  species = c("Pmaculatus", "Pleopardus", "Pmaculatus"),
  count = c(5, 2, 8))

# Force inclusion of hidden zero-catch data
full_catch_matrix <- raw_catch |>
  complete(site, species, fill = list(count = 0))

print(full_catch_matrix)
## # A tibble: 4 × 3
##   site   species    count
##   <chr>  <chr>      <dbl>
## 1 Reef_1 Pleopardus     2
## 2 Reef_1 Pmaculatus     5
## 3 Reef_2 Pleopardus     0
## 4 Reef_2 Pmaculatus     8
sensor_log <- tibble(
  day = 1:4,
  salinity = c(35.2, 35.1, NA, 35.3)
)

# Remove any row where salinity is missing
clean_log <- sensor_log |>
  drop_na(salinity)

## Practical Exercises: Penguins, Pivots, and Joining Data

# Make sure packages are loaded
library(tidyverse)
library(palmerpenguins)
library(lubridate)

# The messy metadata provided by your colleague
island_metadata <- tibble(
  island_name = c(" biscoe", "Dream ", "Torgersen"),
  station_install = c("15/01/2003", "22-03-2004", "05/11/2001"),
  latitude = c(-64.81, -64.73, -64.76)
)

print(island_metadata)
## # A tibble: 3 × 3
##   island_name station_install latitude
##   <chr>       <chr>              <dbl>
## 1 " biscoe"   15/01/2003         -64.8
## 2 "Dream "    22-03-2004         -64.7
## 3 "Torgersen" 05/11/2001         -64.8
clean_metadata <- island_metadata %>%
  mutate(
    island_name = str_to_title(str_squish(island_name)),
    station_install = dmy(station_install)
  )

print(clean_metadata)
## # A tibble: 3 × 3
##   island_name station_install latitude
##   <chr>       <date>             <dbl>
## 1 Biscoe      2003-01-15         -64.8
## 2 Dream       2004-03-22         -64.7
## 3 Torgersen   2001-11-05         -64.8
penguins_spatial <- penguins %>%
  left_join(
    clean_metadata,
    by = join_by(island == island_name)
  )

penguins_spatial %>%
  select(species, island, station_install, latitude) %>%
  head ()
## # A tibble: 6 × 4
##   species island    station_install latitude
##   <fct>   <chr>     <date>             <dbl>
## 1 Adelie  Torgersen 2001-11-05         -64.8
## 2 Adelie  Torgersen 2001-11-05         -64.8
## 3 Adelie  Torgersen 2001-11-05         -64.8
## 4 Adelie  Torgersen 2001-11-05         -64.8
## 5 Adelie  Torgersen 2001-11-05         -64.8
## 6 Adelie  Torgersen 2001-11-05         -64.8
nrow(penguins_spatial) == nrow(penguins)
## [1] TRUE
sum(is.na(penguins_spatial$station_install))
## [1] 0
maximum_mass_table <- penguins_spatial %>%
  drop_na(body_mass_g) %>%
  group_by(species, island) %>%
  summarise(
    max_body_mass_g = max(body_mass_g),
    .groups = "drop"
  ) %>%
  pivot_wider(
    names_from = island,
    values_from = max_body_mass_g
  )

maximum_mass_table
## # A tibble: 3 × 4
##   species   Biscoe Dream Torgersen
##   <fct>      <int> <int>     <int>
## 1 Adelie      4775  4650      4700
## 2 Chinstrap     NA  4800        NA
## 3 Gentoo      6300    NA        NA