WS1102

setup
if (!nzchar(system.file(package = "librarian"))) {
  install.packages("librarian")
}

librarian::shelf(
  quiet = TRUE,
  readr, here, fs, ggplot2, glue, "jiho/castr", dplyr, oce, patchwork, purrr, tidyr
)
Code
source(here("R/cruise_load.R"))
cruise_df <- cruise_load(params$cruise_id)
plot depth & pressure vs time elapsed
tryCatch({
  plots <- list()
  
  for (station_name in unique(cruise_df$station)) {
    subset_df <- filter(cruise_df, station == station_name)
    plots[[station_name]] <- ggplot(subset_df, aes(x = time_elapsed)) +
      geom_point(aes(y = depth), color = "blue") +  # Plot depth in blue
      geom_line(aes(y = sea_water_pressure), color = "red") +  # Plot sea water pressure in red
      ggtitle(glue("{station_name}")) +
      theme(
        axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        axis.text.x = element_blank(),
        axis.text.y = element_blank(),
        axis.ticks.x = element_blank(),
        axis.ticks.y = element_blank()
      )  # Remove individual axis titles and text
  }
  
  # drop nulls
  plots <- purrr::compact(plots)
  
  # Combine all plots into a grid
  combined_plot <- wrap_plots(plots) + 
    plot_layout(ncol = 4) +  # Adjust ncol to set number of columns in the grid
    plot_annotation(
      title = "Depth (blue) and Pressure (red)",
      subtitle = "Each panel represents a different station",
      caption = "Time Elapsed (x-axis) vs Depth & Pressure (y-axis)"
    ) +
    theme(
      plot.tag = element_text(size = 12, face = "bold"),
      plot.tag.position = "topleft",
      axis.title.x = element_text(margin = margin(t = 10)),
      axis.title.y = element_text(margin = margin(r = 10))
    )
  
  print(combined_plot)
}, error = function(er){
  print(er)
});

plot across all stations
p <- ggplot(cruise_df, aes(x = time, y = depth, fill = station)) +
  geom_col() +  # This creates the bars
  # geom_text(aes(label = station), vjust = -0.3) +  # This adds labels to each bar, adjust vjust for position
  labs(x = "Time", y = "Depth", title = "Depth over Time by Station") +  # Set labels and title
  theme_minimal()  # Use a minimal theme
print(p)

create oce.ctd objects from dataframes
ctd_load <- function(data, other_params = NULL) {
  
  # create csv into ctd object
  test_ctd <-
    as.ctd(
      salinity    = data$sea_water_salinity,
      temperature = data$sea_water_temperature,
      pressure    = data$sea_water_pressure,
      station     = data$station
    )
  
  # add additional columns to ctd object
  if (!is.null(other_params)) {
    for (param_name in other_params) {
      test_ctd <-
        oceSetData(
          object = test_ctd,
          name   = param_name,
          value  = data[[param_name]]
        )
    }
  }
  print(glue("{data$station[1]}:\t{length(test_ctd@data$scan)} scans"))


  return(test_ctd)
}

# Define other parameters to add
other_params <- c(
  "cruise_id", "station", "time", "time_elapsed", 
  "latitude", "longitude", "sea_water_electrical_conductivity", 
  "CDOM", "dissolved_oxygen","oxygen_saturation", "chlorophyll_concentration", 
  "chlorophyll_fluorescence", "photosynthetically_available_radiation", 
  "beam_attenuation","beam_transmission", "depth", "sea_water_sigma_t",
  "descent_rate", "sound_velocity","altimeter"
)

# Split data by station and create data list
ctd_FK <- cruise_df %>%
  split(.$station) %>%
  map(~ ctd_load(.x, other_params = other_params)) # ~ is a lambda(x)
1:  3269 scans
16: 1622 scans
17: 3069 scans
18: 2063 scans
19: 738 scans
20: 1260 scans
21.5:   5507 scans
22.5:   4914 scans
23: 1831 scans
24: 3167 scans
25.5:   13047 scans
28: 1874 scans
29.5:   2666 scans
3:  7964 scans
31: 2054 scans
34: 1769 scans
39: 2308 scans
42: 1729 scans
49: 1637 scans
50: 1646 scans
53: 1766 scans
54: 611 scans
56: 902 scans
57: 605 scans
59: 1528 scans
6.5:    5481 scans
60: 679 scans
68: 1554 scans
69: 1132 scans
7:  1107 scans
9:  2737 scans
9.5:    10626 scans
BLOOM:  7720 scans
DT.9:   3518 scans
plotting scans for each cast in the first list
for (i in seq(ctd_FK)){
  cast <- ctd_FK[[i]]  # 1 is selecting only the first sublist
  # print(i)
  print(glue("=== station: {cast@metadata$station[1]}"))
  print(glue("# scans: {length(cast@data$scan)}"))
  plotScan(cast)
}
=== station: 1
# scans: 3269

=== station: 16
# scans: 1622

=== station: 17
# scans: 3069

=== station: 18
# scans: 2063

=== station: 19
# scans: 738

=== station: 20
# scans: 1260

=== station: 21.5
# scans: 5507

=== station: 22.5
# scans: 4914

=== station: 23
# scans: 1831

=== station: 24
# scans: 3167

=== station: 25.5
# scans: 13047

=== station: 28
# scans: 1874

=== station: 29.5
# scans: 2666

=== station: 3
# scans: 7964

=== station: 31
# scans: 2054

=== station: 34
# scans: 1769

=== station: 39
# scans: 2308

=== station: 42
# scans: 1729

=== station: 49
# scans: 1637

=== station: 50
# scans: 1646

=== station: 53
# scans: 1766

=== station: 54
# scans: 611

=== station: 56
# scans: 902

=== station: 57
# scans: 605

=== station: 59
# scans: 1528

=== station: 6.5
# scans: 5481

=== station: 60
# scans: 679

=== station: 68
# scans: 1554

=== station: 69
# scans: 1132

=== station: 7
# scans: 1107

=== station: 9
# scans: 2737

=== station: 9.5
# scans: 10626

=== station: BLOOM
# scans: 7720

=== station: DT.9
# scans: 3518

plotting each cast in the first list
for (i in seq(ctd_FK)){
  cast <- ctd_FK[[i]]  # 1 is selecting only the first sublist
  tryCatch({
    plot(ctdDecimate(ctdTrim(cast)))
  }, error = function(e){
    print(e)
  })
}

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 3269' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 1622' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 3069' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 2063' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 738' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 1260' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 5507' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 4914' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 1831' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 3167' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 13047' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 1874' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 2666' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 7964' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 2054' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 1769' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 2308' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 1729' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 1637' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 1646' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 1766' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 611' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 902' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 605' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 1528' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 5481' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 679' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 1554' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 1132' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 1107' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 2737' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 10626' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 7720' in coercion to 'logical(1)'>

<simpleError in !is.null(x@metadata$station) && !is.na(x@metadata$station): 'length = 3518' in coercion to 'logical(1)'>
plotting other physical parameters for each cast
# Loop through each CTD cast
for (i in seq(ctd_FK)){
  cast <- ctd_FK[[i]]  # Assuming each sublist contains only one relevant CTD object
  tryCatch({
    # Extract metadata for station name and cruise ID
    station_name <- cast@metadata$station[1]
    cruise_id <- cast@data$cruise_id[1]

    # Generate a title with station name and cruise ID
    overall_title <- glue::glue("Station: {station_name}, Cruise ID: {cruise_id}")

    # Set margins: increase the outer margin for the title
    par(oma = c(0, 0, 3, 0))  # Top outer margin increased for title

    # Plotting function with specific parameters
    oce::plot(
      x = ctdDecimate(ctdTrim(cast)),
      which = c(
        "sea_water_electrical_conductivity",
        "descent_rate", "sound_velocity",
        "sea_water_sigma_t","altimeter"
      ),
      main = ""  # No main title for individual subplots
    )

    # Place a single overall title at the top of the plot frame
    mtext(overall_title, side = 3, line = 1, outer = TRUE, cex = 1.5)

    # Reset outer margins to default
    par(oma = c(0, 0, 0, 0))

  }, error = function(e) {
    print(e$message)  # Print any errors that occur during plotting
  })
}

[1] "need finite 'xlim' values"
[1] "need finite 'xlim' values"
[1] "need finite 'xlim' values"
plotting other nutrient parameters for each cast
# Loop through each CTD cast
for (i in seq(ctd_FK)){
  cast <- ctd_FK[[i]]  # Assuming each sublist contains only one relevant CTD object
  tryCatch({
    # Extract metadata for station name and cruise ID
    station_name <- cast@metadata$station[1]
    cruise_id <- cast@data$cruise_id[1]

    # Generate a title with station name and cruise ID
    overall_title <- glue::glue("Station: {station_name}, Cruise ID: {cruise_id}")

    # Set margins: increase the outer margin for the title
    par(oma = c(0, 0, 3, 0))  # Top outer margin increased for title

    # Plotting function with specific parameters
    oce::plot(
      x = ctdDecimate(ctdTrim(cast)),
      which = c(
        "CDOM", "dissolved_oxygen",
        "oxygen_saturation",
        "chlorophyll_concentration", "chlorophyll_fluorescence"
      ),
      main = ""  # No main title for individual subplots
    )

    # Place a single overall title at the top of the plot frame
    mtext(overall_title, side = 3, line = 1, outer = TRUE, cex = 1.5)

    # Reset outer margins to default
    par(oma = c(0, 0, 0, 0))

  }, error = function(e) {
    print(e$message)  # Print any errors that occur during plotting
  })
}
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
[1] "In plot,ctd-method() : which=\"CDOMdissolved_oxygenoxygen_saturationchlorophyll_concentrationchlorophyll_fluorescence\" cannot be handled"
plotting other optical parameters for each cast
# Loop through each CTD cast
for (i in seq(ctd_FK)){
  cast <- ctd_FK[[i]]  # Assuming each sublist contains only one relevant CTD object
  tryCatch({
    # Extract metadata for station name and cruise ID
    station_name <- cast@metadata$station[1]
    cruise_id <- cast@data$cruise_id[1]

    # Generate a title with station name and cruise ID
    overall_title <- glue::glue("Station: {station_name}, Cruise ID: {cruise_id}")

    # Set margins: increase the outer margin for the title
    par(oma = c(0, 0, 3, 0))  # Top outer margin increased for title

    # Plotting function with specific parameters
    oce::plot(
      x = ctdDecimate(ctdTrim(cast)),
      which = c(
        "photosynthetically_available_radiation",
        "beam_attenuation","beam_transmission"
      ),
      main = ""  # No main title for individual subplots
    )

    # Place a single overall title at the top of the plot frame
    mtext(overall_title, side = 3, line = 1, outer = TRUE, cex = 1.5)

    # Reset outer margins to default
    par(oma = c(0, 0, 0, 0))

  }, error = function(e) {
    print(e$message)  # Print any errors that occur during plotting
  })
}

loop through every cast, clean, & save
combined_df <- data.frame()
for (i in seq(ctd_FK)){
  tryCatch({
    cast <- ctd_FK[[i]]  # 1 is selecting only the first sublist
    
    # print(class(cast))
    # clean cast 
    trimmed_cast <- ctdTrim(cast)
    decimated_cast <- ctdDecimate(trimmed_cast, p = 0.5)  # binned to 0.5 m
    
    # convert to df
    cast_df <- as.data.frame(decimated_cast@data)
    
    # Add metadata
    # assumes station ID and cruise ID the same for all & just uses 1st one
    cast_df <- mutate(
      cast_df,
      station = cast@data$station[1],
      cruise_id = cast@data$cruise_id[1]
    )
  
    # drop NA rows left by cleaning
    cast_df <- subset(cast_df, !is.na(scan))
    
    # Append the data to the combined dataframe
    combined_df <- rbind(combined_df, cast_df)
  }, error = function(e){
    print(glue("error in cast {cast@metadata$station[1]}"))
    print(e)
  })
}
# Save to CSV
file_path <- here(glue("data/cleaned/{cruise_id}.csv"))
write.csv(combined_df, file_path, row.names = FALSE)