# Missing values in summaries: na.rm and false zeros
# https://tidyecology.com/posts/missing-values-in-summaries/
#
# 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-09-27

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

te_paper  <- "#f5f4ee"
te_ink    <- "#16241d"
te_body   <- "#2c3a31"
te_forest <- "#275139"
te_rust   <- "#b5534e"
te_gold   <- "#c9b458"
te_line   <- "#dad9ca"

theme_datasheet <- function() {
  theme_minimal(base_size = 12) +
    theme(plot.background  = element_rect(fill = te_paper, colour = NA),
          panel.background = element_rect(fill = te_paper, colour = NA),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          text             = element_text(colour = te_body),
          axis.text        = element_text(colour = te_body),
          legend.position  = "top")
}

## ---- na-rules ----
one_gap    <- c(8, NA, 30, 35, 22, 11)   # May not walked
no_walks   <- rep(NA_real_, 6)           # nobody walked all season

sum(one_gap)
sum(one_gap, na.rm = TRUE)
mean(one_gap, na.rm = TRUE)
c(length = length(one_gap), walked = sum(!is.na(one_gap)))

species_seen <- c("Maniola jurtina", "Pieris rapae", NA, "Maniola jurtina")   # one name not recorded (NA)
c(distinct = length(unique(species_seen)), species = length(unique(na.omit(species_seen))))

sum(no_walks, na.rm = TRUE)
mean(no_walks, na.rm = TRUE)
suppressWarnings(max(no_walks, na.rm = TRUE))

max_warned <- tryCatch({ max(no_walks, na.rm = TRUE); FALSE },
                       warning = function(w) TRUE)
stopifnot(is.na(sum(one_gap)),                                  # one NA spoils the sum
          sum(one_gap, na.rm = TRUE) == 106,                    # the NA is dropped
          mean(one_gap, na.rm = TRUE) == 106 / 5,               # divided by 5, not 6
          length(one_gap) == 6, sum(!is.na(one_gap)) == 5,      # length() counts the NA
          length(unique(species_seen)) == 3,                    # unique() keeps NA as a value
          length(unique(na.omit(species_seen))) == 2,           # ... unless it is removed
          identical(read.csv(text = "walk,species\n1,\n2,Pieris rapae")$species[1], ""),  # a blank text cell is "", not NA
          sum(no_walks, na.rm = TRUE) == 0,                     # nothing left: zero
          is.nan(mean(no_walks, na.rm = TRUE)),                 # nothing left: NaN
          suppressWarnings(max(no_walks, na.rm = TRUE)) == -Inf, # nothing left: -Inf
          max_warned,                                           # ... with a warning
          rowSums(rbind(one_gap, no_walks), na.rm = TRUE) == c(106, 0),  # rowSums() alike
          colSums(cbind(one_gap, no_walks), na.rm = TRUE) == c(106, 0))  # colSums() alike

## ---- one-transect ----
years      <- 2005:2024
months     <- c("Apr", "May", "Jun", "Jul", "Aug", "Sep")
month_mean <- c(8, 16, 28, 32, 24, 12)            # expected count per walk, 120 a season
p_missed   <- seq(0.05, 0.40, length.out = length(years))

simulate_transect <- function(p_month = matrix(p_missed, length(years), 6)) {
  counts <- matrix(rpois(length(years) * 6, rep(month_mean, each = length(years))),
                   nrow = length(years), dimnames = list(years, months))
  missed <- matrix(runif(length(years) * 6), nrow = length(years)) < p_month
  counts[missed] <- NA
  counts
}

set.seed(1612)
counts <- simulate_transect()
counts[c("2005", "2015", "2024"), ]

## ---- yearly-table ----
yearly <- data.frame(year     = years,
                     total    = rowSums(counts, na.rm = TRUE),
                     walked   = rowSums(!is.na(counts)))
yearly$per_walk <- yearly$total / yearly$walked      # NaN in a year with no walks
stopifnot(all.equal(yearly$per_walk, unname(rowMeans(counts, na.rm = TRUE))))

per_decade <- function(slope) 100 * (exp(10 * slope) - 1)   # log-scale slope as per cent per decade
fit_naive  <- glm(total ~ year, family = poisson, data = yearly)
naive_decade <- per_decade(coef(fit_naive)[["year"]])
c(naive_per_decade = round(naive_decade, 1),
  walks_first_5_years = sum(yearly$walked[1:5]),
  walks_last_5_years  = sum(yearly$walked[16:20]))

## ---- replicates ----
expected_total <- 120 * (1 - p_missed)
closed_slope   <- coef(glm(expected_total ~ years, family = quasipoisson))[["years"]]
stopifnot(isTRUE(all.equal(closed_slope,                # same slope as poisson
  suppressWarnings(coef(glm(expected_total ~ years, family = poisson)))[["years"]])))

trend_pair <- function(counts) {
  total  <- rowSums(counts, na.rm = TRUE)
  walked <- rowSums(!is.na(counts))
  keep   <- walked > 0                                 # a year with no walks is unknown
  month  <- factor(rep(months, each = length(years)), levels = months)
  c(naive  = coef(glm(total ~ years, family = poisson))[["years"]],
    offset = coef(glm(total[keep] ~ years[keep] + offset(log(walked[keep])),
                      family = poisson))[[2]],
    month  = coef(glm(as.vector(counts) ~ rep(years, 6) + month,
                      family = poisson))[[2]],
    zero_years = sum(walked == 0))
}

set.seed(2016)
n_rep <- 2000
reps  <- t(replicate(n_rep, trend_pair(simulate_transect())))

naive_mean  <- mean(reps[, "naive"])
naive_mcse  <- sd(reps[, "naive"]) / sqrt(n_rep)
naive_neg   <- mean(reps[, "naive"] < 0)
naive_neg_se <- sqrt(naive_neg * (1 - naive_neg) / n_rep)
zero_share  <- mean(reps[, "zero_years"] > 0)
zero_expect <- sum(p_missed^6)                         # expected all-missed years per series
zero_prob   <- 1 - prod(1 - p_missed^6)                # chance of at least one such year
round(c(closed_per_decade = per_decade(closed_slope),
        sim_per_decade = per_decade(naive_mean),
        slope_gap_in_mcse = (naive_mean - closed_slope) / naive_mcse,
        share_negative = naive_neg, mcse = naive_neg_se,
        series_with_a_zero_year = zero_share, expected_zero_years = zero_expect,
        chance_of_a_zero_year = zero_prob), 4)

## ---- monthly-glm ----
long <- data.frame(year  = rep(years, times = 6),
                   month = factor(rep(months, each = length(years)), levels = months),
                   count = as.vector(counts))
fit_month  <- glm(count ~ year, family = poisson, data = long)
fit_offset <- glm(total ~ year + offset(log(walked)), family = poisson,
                  data = yearly[yearly$walked > 0, ])

stopifnot(identical(getOption("na.action"), "na.omit"),
          is.nan(rowMeans(rbind(no_walks), na.rm = TRUE)),               # empty year: NaN
          length(fitted(glm(c(1, 2, NaN, 4) ~ seq_len(4), family = poisson))) == 3,
          length(fitted(fit_month)) == sum(!is.na(long$count)),   # missing rows dropped
          isTRUE(all.equal(coef(fit_month)[["year"]], coef(fit_offset)[["year"]],
                           tolerance = 1e-6)))
month_decade <- per_decade(coef(fit_month)[["year"]])

offset_mean   <- mean(reps[, "offset"])
offset_mcse   <- sd(reps[, "offset"]) / sqrt(n_rep)
offset_neg    <- mean(reps[, "offset"] < 0)
offset_neg_se <- sqrt(offset_neg * (1 - offset_neg) / n_rep)
month_mean_slope <- mean(reps[, "month"])
month_mcse    <- sd(reps[, "month"]) / sqrt(n_rep)
slope_sd      <- 10 * 100 * apply(reps[, c("offset", "month")], 2, sd)   # spread across transects
round(c(this_transect = month_decade,
        sim_per_decade = per_decade(offset_mean),
        mcse_per_decade = 10 * 100 * offset_mcse,
        share_negative = offset_neg, mcse = offset_neg_se,
        month_term_per_decade = per_decade(month_mean_slope),
        month_term_mcse = 10 * 100 * month_mcse,
        sd_without_month = slope_sd[["offset"]], sd_with_month = slope_sd[["month"]]), 4)

## ---- fig-totals ----
plot_df <- rbind(
  data.frame(year = years, value = yearly$total, series = "sum(na.rm = TRUE)"),
  data.frame(year = years, value = 6 * yearly$per_walk, series = "6 x mean per walked month"))
plot_df$series <- factor(plot_df$series, levels = c("sum(na.rm = TRUE)", "6 x mean per walked month"))
line_df <- rbind(
  data.frame(year = years, value = fitted(fit_naive), series = "sum(na.rm = TRUE)"),
  data.frame(year = years, value = 6 * exp(coef(fit_month)[[1]] + coef(fit_month)[[2]] * years),
             series = "6 x mean per walked month"))
line_df$series <- factor(line_df$series, levels = levels(plot_df$series))

ggplot(plot_df, aes(year, value, colour = series)) +
  geom_hline(yintercept = 120, colour = te_ink, linetype = "dotted", linewidth = 0.7) +
  geom_line(data = line_df, linewidth = 1) +
  geom_point(size = 2.4) +
  annotate("text", x = years, y = 12, label = yearly$walked, colour = te_body, size = 3.2) +
  annotate("text", x = 2004.2, y = 12, label = "walks", colour = te_body, size = 3.2, hjust = 1) +
  annotate("text", x = 2002.7, y = 120, label = "true: 120", colour = te_ink,
           size = 3.3, hjust = 0, vjust = -0.5) +
  scale_colour_manual(values = c(te_rust, te_forest), name = NULL) +
  scale_x_continuous(breaks = seq(2005, 2024, 5), limits = c(2002.6, 2024.6)) +
  scale_y_continuous(limits = c(0, NA)) +
  labs(x = NULL, y = "butterflies per season") +
  theme_datasheet()

## ---- edge-months ----
edge_months <- c("Apr", "May", "Sep")
p_edge <- matrix(0, length(years), 6, dimnames = list(years, months))
p_edge[, edge_months] <- 2 * p_missed                 # same expected share missed per year
stopifnot(isTRUE(all.equal(rowMeans(p_edge), p_missed, check.attributes = FALSE)))

trend_edge <- function(counts) {
  long <- data.frame(year  = rep(years, times = 6),
                     month = factor(rep(months, each = length(years)), levels = months),
                     count = as.vector(counts))
  c(naive       = coef(glm(rowSums(counts, na.rm = TRUE) ~ years, family = poisson))[["years"]],
    per_walk    = coef(glm(count ~ year, family = poisson, data = long))[["year"]],
    month_term  = coef(glm(count ~ year + month, family = poisson, data = long))[["year"]])
}

set.seed(2017)
reps_edge <- t(replicate(n_rep, trend_edge(simulate_transect(p_edge))))
edge_decade <- per_decade(colMeans(reps_edge))
edge_mcse   <- 10 * 100 * apply(reps_edge, 2, sd) / sqrt(n_rep)
edge_up     <- mean(reps_edge[, "per_walk"] > 0)
round(rbind(per_decade = edge_decade, mcse = edge_mcse), 2)
c(share_per_walk_rising = edge_up)
