# Dates and times in ecological data
# https://tidyecology.com/posts/dates-and-times-in-ecological-data/
#
# The R code of this Tidy Ecology tutorial, chunk by chunk, in the order of the post.
# Run it top to bottom in a fresh R session. Code the post shows but does not run
# is commented out. The prose, and the numbers it quotes, are in the post itself.
# Post last modified: 2026-10-01

## ---- setup ----
library(ggplot2)

te_pal <- list(forest = "#275139", green = "#2f8f63", sage = "#93a87f",
               clay = "#b5534e", gold = "#cda23f", line = "#dad9ca",
               ink = "#16241d", paper = "#f5f4ee")

theme_te <- function() {
  theme_minimal(base_size = 12) +
    theme(panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#e7e6dc"),
          plot.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          plot.title = element_text(face = "bold", colour = te_pal$ink),
          axis.title = element_text(colour = "#2c3a31"))
}

## ---- field-dates ----
set.seed(20260818)
n_site <- 180
elev <- round(runif(n_site, 200, 1400))
doy_2018 <- round(96.0 + 3.0 * (elev - 200) / 100 + rnorm(n_site, 0, 4.2))
doy_2019 <- round(94.8 + 3.0 * (elev - 200) / 100 + rnorm(n_site, 0, 4.2))
d_2018 <- as.Date("2018-01-01") + doy_2018 - 1
d_2019 <- as.Date("2019-01-01") + doy_2019 - 1

source_2019 <- ifelse(elev >= 700, "scheme",
               ifelse(elev >= 450, "partner", "volunteers"))
written_2018 <- format(d_2018, "%Y-%m-%d")
written_2019 <- ifelse(source_2019 == "scheme", format(d_2019, "%Y-%m-%d"),
                ifelse(source_2019 == "partner", format(d_2019, "%d/%m/%Y"),
                       format(d_2019, "%d.%m.%y")))
print(table(source_2019))
print(head(data.frame(elevation = elev, source = source_2019,
                      written = written_2019), 6))

## ---- naive-parse ----
read_2018 <- as.Date(written_2018, format = "%Y-%m-%d")
read_2019 <- as.Date(written_2019, format = "%Y-%m-%d")
got_2018 <- as.numeric(format(read_2018, "%j"))
got_2019 <- as.numeric(format(read_2019, "%j"))

q10 <- function(x) as.numeric(quantile(x, 0.10, na.rm = TRUE, names = FALSE))
q90 <- function(x) as.numeric(quantile(x, 0.90, na.rm = TRUE, names = FALSE))
true_change <- mean(doy_2019) - mean(doy_2018)
naive_change <- mean(got_2019, na.rm = TRUE) - mean(got_2018, na.rm = TRUE)
f_true <- lm(doy_2019 ~ I(elev / 100))
f_kept <- lm(got_2019 ~ I(elev / 100))

round(c(sites = n_site,
        rows_lost = sum(is.na(read_2019)),
        rows_lost_percent = 100 * mean(is.na(read_2019)),
        highest_lost_site_metres = max(elev[is.na(read_2019)]),
        mean_elevation_kept = mean(elev[!is.na(read_2019)]),
        mean_elevation_lost = mean(elev[is.na(read_2019)]),
        true_mean_doy_2018 = mean(doy_2018),
        true_mean_doy_2019 = mean(doy_2019),
        true_change_days = true_change,
        reported_mean_doy_2019 = mean(got_2019, na.rm = TRUE),
        reported_change_days = naive_change,
        error_days = naive_change - true_change,
        true_start_of_season = q10(doy_2019),
        reported_start_of_season = q10(got_2019),
        start_shift_days = q10(got_2019) - q10(doy_2019),
        true_season_span = q90(doy_2019) - q10(doy_2019),
        reported_season_span = q90(got_2019) - q10(got_2019),
        true_slope_days_per_100m = coef(f_true)[2],
        kept_slope_days_per_100m = coef(f_kept)[2],
        true_slope_se = summary(f_true)$coefficients[2, 2],
        kept_slope_se = summary(f_kept)$coefficients[2, 2],
        se_inflation = summary(f_kept)$coefficients[2, 2] /
          summary(f_true)$coefficients[2, 2]), 4)

## ---- fig-lost ----
lost_df <- data.frame(
  elevation = elev, doy = doy_2019,
  fate = factor(ifelse(is.na(read_2019), "Returned NA, dropped in silence",
                       "Matched the format, kept"),
                levels = c("Matched the format, kept",
                           "Returned NA, dropped in silence")))

ggplot(lost_df, aes(elevation, doy, colour = fate)) +
  geom_vline(xintercept = 700, linetype = 3, colour = te_pal$ink,
             linewidth = 0.9) +
  geom_hline(yintercept = mean(doy_2019), linetype = 2,
             colour = te_pal$forest, linewidth = 0.9) +
  geom_hline(yintercept = mean(got_2019, na.rm = TRUE), linetype = 2,
             colour = te_pal$clay, linewidth = 0.9) +
  geom_point(size = 2.5, alpha = 0.9) +
  annotate("text", x = 715, y = max(doy_2019), hjust = 0, size = 3.4,
           colour = te_pal$ink,
           label = "700 m: below here the other two sources recorded") +
  annotate("text", x = 1385, y = mean(doy_2019) - 3.8, hjust = 1, size = 3.4,
           colour = te_pal$forest, label = "Mean over all 180 sites: day 113.3") +
  annotate("text", x = 215, y = mean(got_2019, na.rm = TRUE) + 3.8, hjust = 0,
           size = 3.4, colour = te_pal$clay,
           label = "Mean over the rows that parsed: day 121.1") +
  scale_colour_manual(values = c(te_pal$sage, te_pal$gold), name = NULL) +
  scale_x_continuous(breaks = c(200, 500, 700, 1000, 1300)) +
  labs(x = "Site elevation (metres)", y = "First flowering (day of year, 2019)",
       title = "Every row as.Date could not read came from below 700 metres") +
  theme_te() +
  theme(legend.position = "top")

## ---- parser ----
parse_field_date <- function(x, formats) {
  out <- rep(as.Date(NA), length(x))
  used <- rep(NA_character_, length(x))
  for (f in formats) {
    todo <- which(is.na(out))
    if (!length(todo)) break
    got <- as.Date(x[todo], format = f)
    ok <- !is.na(got)
    out[todo[ok]] <- got[ok]
    used[todo[ok]] <- f
  }
  list(date = out, format = used)
}

careless <- parse_field_date(written_2019, c("%Y-%m-%d", "%d/%m/%Y", "%d.%m.%Y"))
careful  <- parse_field_date(written_2019, c("%Y-%m-%d", "%d/%m/%Y", "%d.%m.%y"))
print(table(as.numeric(format(careless$date, "%Y"))))
print(table(careful$format))
print(c(as.Date("17.04.19", "%d.%m.%Y"), as.Date("17.04.19", "%d.%m.%y"),
        as.Date("17.04.68", "%d.%m.%y"), as.Date("17.04.69", "%d.%m.%y")))

## ---- parser-scores ----
year_careless <- as.numeric(format(careless$date, "%Y"))
round(c(careless_unparsed = sum(is.na(careless$date)),
        careless_rows_in_year_19 = sum(year_careless < 1000),
        careless_mean_doy = mean(as.numeric(format(careless$date, "%j"))),
        careless_span_days = as.numeric(diff(range(careless$date))),
        careful_unparsed = sum(is.na(careful$date)),
        careful_rows_matching_truth = sum(careful$date == d_2019),
        careful_change_days = mean(as.numeric(format(careful$date, "%j"))) -
          mean(doy_2018),
        rows_flagged_by_a_year_range_check = sum(year_careless != 2019)), 4)

## ---- ambiguity ----
all_2019 <- seq(as.Date("2019-01-01"), as.Date("2019-12-31"), by = "day")
dom <- as.numeric(format(all_2019, "%d"))
mon <- as.numeric(format(all_2019, "%m"))
round(c(days_in_the_year = length(all_2019),
        both_readings_valid = sum(dom <= 12),
        both_readings_valid_percent = 100 * mean(dom <= 12),
        transpose_to_themselves = sum(dom == mon),
        genuinely_damaging = sum(dom <= 12 & dom != mon),
        genuinely_damaging_percent = 100 * mean(dom <= 12 & dom != mon),
        rows_needed_to_expose_the_swap = 1 / (1 - mean(dom <= 12))), 4)

## ---- slash-swap ----
slash <- written_2019[source_2019 == "partner"]
as_written <- as.Date(slash, format = "%d/%m/%Y")
as_swapped <- as.Date(slash, format = "%m/%d/%Y")
round(c(slash_rows = length(slash),
        swapped_to_na = sum(is.na(as_swapped)),
        swapped_to_na_percent = 100 * mean(is.na(as_swapped)),
        swapped_silently = sum(!is.na(as_swapped)),
        swapped_silently_percent = 100 * mean(!is.na(as_swapped)),
        mean_doy_as_written = mean(as.numeric(format(as_written, "%j"))),
        mean_doy_of_the_survivors =
          mean(as.numeric(format(as_swapped, "%j")), na.rm = TRUE)), 4)

## ---- transect ----
set.seed(20260818)
visit_month <- rep(3:10, each = 2)
visit_day <- as.integer(rep(c(3, 10), 8) + sample(-2:2, 16, replace = TRUE))
visit_day <- pmin(pmax(visit_day, 1), 12)
visit <- as.Date(sprintf("2019-%02d-%02d", visit_month, visit_day))
flight_peak <- as.Date("2019-07-14")
count <- round(190 * exp(-0.5 * (as.numeric(visit - flight_peak) / 19)^2)) + 1
recorded <- format(visit, "%d/%m/%Y")

walked <- as.Date(recorded, format = "%d/%m/%Y")
guessed <- as.Date(recorded, format = "%m/%d/%Y")
print(data.frame(recorded, count, read_as = as.character(guessed)))

## ---- transect-damage ----
wmean_date <- function(d, w) sum(as.numeric(d) * w) / sum(w)
as_day <- function(v) as.Date(round(v), origin = "1970-01-01")
wm_walked <- wmean_date(walked, count)
wm_guessed <- wmean_date(guessed, count)
pair_flip <- function(a, b) {
  ij <- upper.tri(diag(length(a)))
  100 * mean(outer(a, a, "-")[ij] * outer(b, b, "-")[ij] < 0)
}
print(c(as.character(as_day(wm_walked)), as.character(as_day(wm_guessed))))
round(c(visits = length(visit),
        rows_returning_na = sum(is.na(guessed)),
        dates_changed = sum(walked != guessed),
        dates_unchanged = sum(walked == guessed),
        peak_count = max(count),
        weighted_mean_doy_walked = as.numeric(format(as_day(wm_walked), "%j")),
        weighted_mean_doy_guessed = as.numeric(format(as_day(wm_guessed), "%j")),
        weighted_mean_shift_days = wm_guessed - wm_walked,
        busiest_visit_doy_walked =
          as.numeric(format(walked[which.max(count)], "%j")),
        busiest_visit_doy_guessed =
          as.numeric(format(guessed[which.max(count)], "%j")),
        largest_single_move_days = max(abs(as.numeric(guessed - walked))),
        season_span_walked = as.numeric(diff(range(walked))),
        season_span_guessed = as.numeric(diff(range(guessed))),
        visit_pairs_out_of_order_percent =
          pair_flip(as.numeric(walked), as.numeric(guessed)),
        spearman = cor(as.numeric(walked), as.numeric(guessed),
                       method = "spearman")), 4)

## ---- fig-swap ----
lev <- c("As read, month first", "As written, day first")
swap_df <- data.frame(
  date = c(walked, guessed), count = rep(count, 2),
  row = factor(rep(c("As written, day first", "As read, month first"), each = 16),
               levels = lev))
seg_df <- data.frame(x = walked, xend = guessed,
                     y = factor("As written, day first", levels = lev),
                     yend = factor("As read, month first", levels = lev))
peak <- which.max(count)
peak_df <- seg_df[peak, ]

ggplot(swap_df, aes(date, row)) +
  geom_segment(data = seg_df, aes(x = x, xend = xend, y = y, yend = yend),
               inherit.aes = FALSE, colour = te_pal$line, linewidth = 0.8) +
  geom_segment(data = peak_df, aes(x = x, xend = xend, y = y, yend = yend),
               inherit.aes = FALSE, colour = te_pal$ink, linewidth = 0.9) +
  geom_vline(xintercept = as_day(wm_walked), linetype = 2, colour = te_pal$forest,
             linewidth = 0.9) +
  geom_vline(xintercept = as_day(wm_guessed), linetype = 2, colour = te_pal$clay,
             linewidth = 0.9) +
  geom_point(aes(size = count, colour = row), alpha = 0.9) +
  annotate("text", x = guessed[peak] - 4, y = 2.5, hjust = 1, size = 3.3,
           colour = te_pal$ink, lineheight = 0.9,
           label = "the busiest visit, 187\nbutterflies, reads as 7 Oct") +
  annotate("text", x = as_day(wm_walked) + 4, y = 0.76, hjust = 0, size = 3.3,
           colour = te_pal$ink, label = "the same visit as written: 10 Jul") +
  annotate("text", x = as_day(wm_guessed) - 4, y = 0.36, hjust = 1, size = 3.3,
           colour = te_pal$clay, label = "weighted mean as read: 6 Jun") +
  annotate("text", x = as_day(wm_walked) + 4, y = 0.36, hjust = 0, size = 3.3,
           colour = te_pal$forest, label = "weighted mean as written: 14 Jul") +
  scale_colour_manual(values = c(te_pal$clay, te_pal$forest), guide = "none") +
  scale_size_area(max_size = 8, name = "Butterflies counted",
                  breaks = c(1, 50, 100, 187)) +
  scale_y_discrete(expand = expansion(add = c(1.15, 1.05))) +
  scale_x_date(date_labels = "%b", date_breaks = "2 months") +
  labs(x = "Date in 2019", y = NULL,
       title = "Sixteen visits, no warnings, and the flight peak lands in October") +
  theme_te() +
  theme(legend.position = "top",
        axis.text.y = element_text(colour = te_pal$ink, size = 10))

## ---- convention ----
date_convention <- function(x) {
  day_first <- as.Date(x, format = "%d/%m/%Y")
  month_first <- as.Date(x, format = "%m/%d/%Y")
  c(rows = length(x),
    decides_day_first = sum(!is.na(day_first) & is.na(month_first)),
    decides_month_first = sum(is.na(day_first) & !is.na(month_first)),
    allows_either = sum(!is.na(day_first) & !is.na(month_first)),
    allows_neither = sum(is.na(day_first) & is.na(month_first)))
}
print(rbind(survey_column = date_convention(slash),
            transect_column = date_convention(recorded)))

## ---- clock-gap ----
tz_site <- "Europe/Budapest"
minute_of_march <- seq(as.POSIXct("2019-03-30 23:00:00", tz = "UTC"),
                       as.POSIXct("2019-03-31 22:59:00", tz = "UTC"), by = "min")
minute_of_october <- seq(as.POSIXct("2019-10-26 22:00:00", tz = "UTC"),
                         as.POSIXct("2019-10-27 22:59:00", tz = "UTC"), by = "min")
local_march <- format(minute_of_march, "%Y-%m-%d %H:%M", tz = tz_site)
local_october <- format(minute_of_october, "%Y-%m-%d %H:%M", tz = tz_site)
march_day <- local_march[substr(local_march, 1, 10) == "2019-03-31"]
october_day <- local_october[substr(local_october, 1, 10) == "2019-10-27"]

t1 <- as.POSIXct("2019-03-31 01:40:00", tz = tz_site)
t2 <- as.POSIXct("2019-03-31 03:20:00", tz = tz_site)
clock_gap <- (3 + 20 / 60) - (1 + 40 / 60)
round(c(minutes_in_31_march = length(march_day),
        distinct_clock_readings_31_march = length(unique(march_day)),
        clock_readings_naming_no_instant = 1440 - length(unique(march_day)),
        minutes_in_27_october = length(october_day),
        distinct_clock_readings_27_october = length(unique(october_day)),
        clock_readings_naming_two_instants = sum(table(october_day) > 1),
        clock_difference_hours = clock_gap,
        elapsed_hours = as.numeric(difftime(t2, t1, units = "hours")),
        overstated_by_minutes =
          60 * (clock_gap - as.numeric(difftime(t2, t1, units = "hours")))), 4)

## ---- ambiguous-hour ----
pair <- as.POSIXct(c("2019-10-27 00:30:00", "2019-10-27 01:30:00"), tz = "UTC")
print(format(pair, "%Y-%m-%d %H:%M:%S", tz = tz_site))
round(c(distinct_utc_instants = length(unique(pair)),
        distinct_local_strings =
          length(unique(format(pair, "%Y-%m-%d %H:%M:%S", tz = tz_site))),
        hours_between_the_instants =
          as.numeric(difftime(pair[2], pair[1], units = "hours"))), 4)

## ---- difftime-units ----
short <- as.POSIXct("2019-05-04 06:30:00", tz = "UTC")
gaps <- c(45, 90, 5400, 200000)
print(data.frame(seconds = gaps,
                 auto_units = sapply(gaps, function(g)
                   attr(difftime(short + g, short), "units")),
                 auto_value = sapply(gaps, function(g)
                   as.numeric(difftime(short + g, short))),
                 forced_hours = round(sapply(gaps, function(g)
                   as.numeric(difftime(short + g, short), units = "hours")), 4)))

## ---- activity ----
set.seed(20260818)
n_night <- 62
per_night <- 9
night_one <- as.Date("2019-03-01")
inst <- unlist(lapply(seq_len(n_night), function(k) {
  midnight <- as.numeric(as.POSIXct(paste0(night_one + k - 1, " 00:00:00"),
                                    tz = "UTC"))
  midnight + 3600 * rnorm(per_night, 19.5 + (1 / 60) * (k - 1), 0.35)
}))
inst <- as.POSIXct(inst, origin = "1970-01-01", tz = "UTC")
logged <- format(inst, "%Y-%m-%d %H:%M:%S", tz = tz_site)
print(head(logged, 4))

## ---- activity-scores ----
hour_of <- function(s) as.numeric(substr(s, 12, 13)) +
  as.numeric(substr(s, 15, 16)) / 60 + as.numeric(substr(s, 18, 19)) / 3600
clock_hour <- hour_of(logged)
recovered <- as.POSIXct(logged, tz = tz_site)
recovered_hour <- hour_of(format(recovered, "%Y-%m-%d %H:%M:%S", tz = "UTC"))
true_hour <- hour_of(format(inst, "%Y-%m-%d %H:%M:%S", tz = "UTC"))
night_index <- rep(seq_len(n_night), each = per_night)
after <- inst >= as.POSIXct("2019-03-31 01:00:00", tz = "UTC")

b_clock <- coef(lm(clock_hour ~ night_index))[2]
b_true <- coef(lm(true_hour ~ night_index))[2]
b_recovered <- coef(lm(recovered_hour ~ night_index))[2]
round(c(detections = length(inst), nights = n_night,
        before_the_change = sum(!after), after_the_change = sum(after),
        clock_sd_hours = sd(clock_hour), true_sd_hours = sd(true_hour),
        sd_inflation = sd(clock_hour) / sd(true_hour),
        mean_clock_hour_before = mean(clock_hour[!after]),
        mean_clock_hour_after = mean(clock_hour[after]),
        clock_step_minutes = 60 * (mean(clock_hour[after]) -
                                     mean(clock_hour[!after])),
        true_step_minutes = 60 * (mean(true_hour[after]) -
                                    mean(true_hour[!after])),
        reported_drift_minutes = 60 * b_clock * (n_night - 1),
        true_drift_minutes = 60 * b_true * (n_night - 1),
        recovered_drift_minutes = 60 * b_recovered * (n_night - 1),
        overstatement_factor = b_clock / b_true,
        overstated_by_minutes = 60 * (b_clock - b_true) * (n_night - 1),
        busiest_true_hour_percent =
          100 * max(table(floor(true_hour))) / length(true_hour),
        busiest_clock_hour_percent =
          100 * max(table(floor(clock_hour))) / length(clock_hour),
        detections_recovered_exactly =
          sum(abs(recovered_hour - true_hour) < 1e-6)), 4)
print(table(floor(clock_hour)))
print(table(floor(true_hour)))

## ---- fig-clock ----
clock_df <- data.frame(
  night = rep(night_index, 2), hour = c(clock_hour, true_hour),
  series = factor(rep(c("Wall clock text in the file",
                        "The same instants in UTC"), each = length(clock_hour)),
                  levels = c("Wall clock text in the file",
                             "The same instants in UTC")))
fit_df <- data.frame(
  intercept = c(coef(lm(clock_hour ~ night_index))[1],
                coef(lm(true_hour ~ night_index))[1]),
  slope = c(b_clock, b_true),
  series = factor(levels(clock_df$series), levels = levels(clock_df$series)))

ggplot(clock_df, aes(night, hour, colour = series)) +
  geom_vline(xintercept = 31, linetype = 2, colour = te_pal$sage,
             linewidth = 0.9) +
  geom_point(size = 1.5, alpha = 0.45) +
  geom_abline(data = fit_df, aes(intercept = intercept, slope = slope,
                                 colour = series),
              linewidth = 1.1, show.legend = FALSE) +
  annotate("text", x = 32.4, y = 18.35, hjust = 0, size = 3.3,
           colour = te_pal$ink, label = "clocks go forward, 31 March") +
  scale_colour_manual(values = c(te_pal$clay, te_pal$forest), name = NULL) +
  scale_y_continuous(breaks = seq(18, 24, 1)) +
  labs(x = "Night of the study (1 March to 1 May 2019)",
       y = "Time of emergence (hours)",
       title = "A 62 minute seasonal drift is reported as 151 minutes") +
  theme_te() +
  theme(legend.position = "top")

## ---- spans ----
spans <- c(1, 2, 4, 5, 10, 20, 50)
print(round(t(sapply(spans, function(s) {
  a <- as.Date("2001-04-18")
  b <- as.Date(paste0(2001 + s, "-04-18"))
  c(years = s, real_days = as.numeric(b - a), times_365 = 365 * s,
    out_by = as.numeric(b - a) - 365 * s,
    out_by_using_365.25 = as.numeric(b - a) - 365.25 * s)
})), 4))

cycle_days <- as.numeric(as.Date("2401-01-01") - as.Date("2001-01-01"))
is_leap <- function(y) (y %% 4 == 0 & y %% 100 != 0) | y %% 400 == 0
print(round(c(days_in_one_400_year_cycle = cycle_days,
              leap_years_in_the_cycle = sum(is_leap(2001:2400)),
              mean_year_days = cycle_days / 400), 4))
print(seq(as.Date("2020-01-31"), by = "month", length.out = 5))
print(as.Date(c("2019-02-29", "2019-04-31"), format = "%Y-%m-%d"))

## ---- leap ----
set.seed(20260818)
season <- 2001:2020
k <- season - 2001
anniversary <- as.Date(paste0(season, "-04-18"))
wobble <- round(residuals(lm(rnorm(length(season), 0, 3.0) ~ k)))
flat_dates <- anniversary + wobble
advance_per_year <- 0.28
advancing_dates <- anniversary + round(wobble - advance_per_year * k)

trend_pair <- function(d) {
  correct <- as.numeric(d - anniversary)
  naive <- as.numeric(d - d[1]) - 365 * k
  a <- summary(lm(correct ~ k))$coefficients[2, ]
  b <- summary(lm(naive ~ k))$coefficients[2, ]
  c(calendar_trend = 10 * a[1], calendar_p = a[4],
    naive_trend = 10 * b[1], naive_p = b[4])
}
leap_days <- as.numeric(anniversary - anniversary[1]) - 365 * k
print(round(rbind(no_real_trend = trend_pair(flat_dates),
                  real_advance = trend_pair(advancing_dates)), 4))
round(c(seasons = length(season),
        built_in_advance_days_per_decade = 10 * advance_per_year,
        leap_days_over_the_series = leap_days[20],
        leap_drift_days_per_decade = 10 * coef(lm(leap_days ~ k))[2],
        real_elapsed_days = as.numeric(anniversary[20] - anniversary[1]),
        naive_elapsed_days = 365 * 19), 4)

## ---- fig-leap ----
panel_df <- function(d, lab) {
  correct <- as.numeric(d - anniversary)
  naive <- as.numeric(d - d[1]) - 365 * k
  data.frame(season = rep(season, 2),
             value = c(correct - correct[1], naive - naive[1]),
             method = rep(c("Exact calendar difference",
                            "365 days per elapsed year"), each = length(season)),
             panel = lab)
}
lab_a <- "A series with no real trend"
lab_b <- sprintf("A series advancing %.1f days per decade", 10 * advance_per_year)
leap_df <- rbind(panel_df(flat_dates, lab_a), panel_df(advancing_dates, lab_b))
leap_df$panel <- factor(leap_df$panel, levels = c(lab_a, lab_b))
leap_df$method <- factor(leap_df$method,
                         levels = c("Exact calendar difference",
                                    "365 days per elapsed year"))

ggplot(leap_df, aes(season, value, colour = method)) +
  geom_hline(yintercept = 0, colour = te_pal$line, linewidth = 0.8) +
  geom_point(size = 2.3, alpha = 0.9) +
  stat_smooth(method = "lm", formula = y ~ x, se = FALSE, linewidth = 1.1) +
  facet_wrap(~panel) +
  scale_colour_manual(values = c(te_pal$forest, te_pal$clay), name = NULL) +
  labs(x = "Season", y = "Days later than the first season",
       title = "One wrong constant invents a trend, then hides a real one") +
  theme_te() +
  theme(legend.position = "top",
        strip.text = element_text(colour = te_pal$ink, face = "bold", size = 9))

## ---- mixed-column ----
set.seed(20260818)
retyped <- sample(seq_along(slash), 11)
mixed <- slash
mixed[retyped] <- format(as_written[retyped], "%m/%d/%Y")
one_format <- as.Date(mixed, format = "%d/%m/%Y")
round(c(column_rows = length(mixed),
        rows_retyped = length(retyped),
        retyped_rows_flagged_as_na = sum(is.na(one_format[retyped])),
        retyped_rows_read_silently = sum(!is.na(one_format[retyped])),
        mean_error_on_the_silent_rows_days =
          mean(abs(as.numeric(one_format[retyped] - as_written[retyped])),
               na.rm = TRUE),
        untouched_rows_still_correct =
          sum(one_format[-retyped] == as_written[-retyped])), 4)
