# Recoding field data in R: ifelse, if_else, case_when
# https://tidyecology.com/posts/recoding-with-case-when/
#
# 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(dplyr)
library(ggplot2)

te_paper  <- "#f5f4ee"
te_ink    <- "#16241d"
te_forest <- "#275139"
te_rust   <- "#b5534e"
te_gold   <- "#c9b458"
te_line   <- "#dad9ca"
te_canvas <- theme(plot.background  = element_rect(fill = te_paper, colour = NA),
                   panel.background = element_rect(fill = te_paper, colour = NA))

## ---- inventory ----
set.seed(1013)
n_stem <- 400
n_unmeasured <- 20

stems <- data.frame(
  stem = sprintf("T%03d", 1:n_stem),
  dbh  = 5 + round(rgamma(n_stem, shape = 2, rate = 0.1))
)
dbh_simulated <- stems$dbh   # kept aside: the sheet never shows these for the lost stems
stems$dbh[sample(n_stem, n_unmeasured)] <- NA

summary(stems$dbh)

## ---- first-match ----
stopifnot(case_when(30 > 10 ~ "pole", 30 > 25 ~ "mature") == "pole")

## ---- wrong-order ----
stems <- stems |>
  mutate(class_lowest_first = case_when(
    dbh >= 10 ~ "pole",
    dbh >= 25 ~ "mature",
    dbh >= 50 ~ "large",
    dbh < 10  ~ "sapling"
  ))
count(stems, class_lowest_first)

## ---- right-order ----
stems <- stems |>
  mutate(size_class = case_when(
    dbh >= 50 ~ "large",
    dbh >= 25 ~ "mature",
    dbh >= 10 ~ "pole",
    dbh < 10  ~ "sapling"
  ))
count(stems, size_class)

n_wrong <- sum(stems$class_lowest_first != stems$size_class, na.rm = TRUE)
n_measured <- sum(!is.na(stems$dbh))
d <- which(stems$class_lowest_first != stems$size_class)
stopifnot(all(stems$class_lowest_first[d] == "pole"),
          identical(d, which(stems$size_class %in% c("mature", "large"))))

## ---- expected-share ----
p_big <- pgamma(19.5, shape = 2, rate = 0.1, lower.tail = FALSE)
p_big

## ---- catch-all ----
stems <- stems |>
  mutate(class_catch_all = case_when(
    dbh >= 50 ~ "large",
    dbh >= 25 ~ "mature",
    dbh >= 10 ~ "pole",
    .default  = "sapling"
  ))
count(stems, class_catch_all)

## ---- na-rules ----
stopifnot(
  case_when(NA_real_ > 10 ~ "pole", .default = "sapling") == "sapling",
  is.na(case_when(NA_real_ > 10 ~ "pole"))
)

share_true  <- mean(stems$size_class == "sapling", na.rm = TRUE)
share_catch <- mean(stems$class_catch_all == "sapling")
n_moved <- sum(is.na(stems$dbh) & stems$class_catch_all == "sapling")
n_moved_small <- sum(is.na(stems$dbh) & dbh_simulated < 10)

## ---- na-first ----
stems <- stems |>
  mutate(class_na_first = case_when(
    is.na(dbh) ~ NA,
    dbh >= 50  ~ "large",
    dbh >= 25  ~ "mature",
    dbh >= 10  ~ "pole",
    .default   = "sapling"
  ))
stopifnot(identical(stems$class_na_first, stems$size_class))

## ---- fig-classes ----
class_levels <- c("sapling", "pole", "mature", "large", "not measured")
version_levels <- c("lowest threshold first", "catch-all for saplings", "highest threshold first")

tally <- bind_rows(
  count(stems, class = class_lowest_first) |> mutate(version = version_levels[1]),
  count(stems, class = class_catch_all)    |> mutate(version = version_levels[2]),
  count(stems, class = size_class)         |> mutate(version = version_levels[3])
) |>
  mutate(class = coalesce(class, "not measured"))

# every class in every version, with 0 where a version has no stems in it
tally <- expand.grid(class = class_levels, version = version_levels,
                     stringsAsFactors = FALSE) |>
  left_join(tally, by = c("class", "version")) |>
  mutate(n = coalesce(n, 0L),
         class = factor(class, levels = class_levels),
         version = factor(version, levels = version_levels))

ggplot(tally, aes(class, n, fill = version)) +
  geom_col(position = position_dodge(width = 0.8), width = 0.78) +
  geom_text(aes(label = n), position = position_dodge(width = 0.8),
            vjust = -0.4, size = 3, colour = te_ink) +
  scale_fill_manual(values = c(te_rust, te_gold, te_forest)) +
  scale_y_continuous(expand = expansion(mult = c(0, 0.08))) +
  labs(x = NULL, y = "number of stems", fill = NULL) +
  theme_minimal(base_size = 12) + te_canvas +
  theme(legend.position = "top", panel.grid.minor = element_blank(),
        panel.grid.major.x = element_blank(),
        text = element_text(colour = te_ink))

## ---- dates ----
plots <- data.frame(
  plot    = sprintf("P%02d", 1:10),
  planned = as.Date("2025-05-05") + 7 * (0:9)
)
plots$visited <- plots$planned + sample(0:3, 10, replace = TRUE)
plots$visited[c(4, 9)] <- NA

filled_base  <- ifelse(is.na(plots$visited), plots$planned, plots$visited)
filled_dplyr <- if_else(is.na(plots$visited), plots$planned, plots$visited)
head(filled_base, 3)
head(filled_dplyr, 3)
stopifnot(is.numeric(filled_base), !inherits(filled_base, "Date"),
          inherits(filled_dplyr, "Date"))

## ---- factor-codes ----
habitat <- factor(c("wood", "fen", "meadow", "fen"))
ifelse(habitat == "fen", "wetland", habitat)
if_else(habitat == "fen", "wetland", habitat)
stopifnot(is.character(if_else(habitat == "fen", "wetland", habitat)),
          is.character(if_else(habitat == "fen", "meadow", habitat)))

## ---- if-else-rules ----
stopifnot(inherits(try(if_else(TRUE, "sapling", 1), silent = TRUE), "try-error"))

stems <- stems |>
  mutate(tree_or_sapling = if_else(dbh >= 10, "tree", "sapling",
                                   missing = "not measured"))
count(stems, tree_or_sapling)
stopifnot(sum(stems$tree_or_sapling == "not measured") == n_unmeasured)

## ---- cut-default ----
breaks <- c(0, 10, 25, 50, Inf)
size_labels <- c("sapling", "pole", "mature", "large")

stems <- stems |>
  mutate(cut_right = cut(dbh, breaks, labels = size_labels),
         cut_left  = cut(dbh, breaks, labels = size_labels, right = FALSE))

stopifnot(cut(10, breaks) == "(0,10]", cut(10, breaks, right = FALSE) == "[10,25)")

n_boundary <- sum(stems$dbh %in% c(10, 25, 50))
n_differ_right <- sum(as.character(stems$cut_right) != stems$size_class, na.rm = TRUE)
n_differ_left  <- sum(as.character(stems$cut_left)  != stems$size_class, na.rm = TRUE)
c(on_a_boundary = n_boundary, default_differs = n_differ_right,
  right_false_differs = n_differ_left)

differs <- which(as.character(stems$cut_right) != stems$size_class)
stopifnot(n_differ_left == 0,
          identical(differs, which(stems$dbh %in% c(10, 25, 50))))

## ---- on-break ----
breaks_on_draw <- c(10, 25, 50) - 5   # the breaks on the scale of the gamma draw
share_on_break <- function(step) {    # step: recording resolution in cm
  sum(pgamma(breaks_on_draw + step / 2, 2, 0.1) -
      pgamma(breaks_on_draw - step / 2, 2, 0.1))
}
on_break <- c(whole_cm = share_on_break(1), tenth_cm = share_on_break(0.1))
on_break

## ---- cut-lowest ----
cover_breaks <- c(0, 5, 25, 50, 75, 100)
stopifnot(is.na(cut(0, cover_breaks)),
          is.na(cut(100, cover_breaks, right = FALSE)),
          !is.na(cut(0, cover_breaks, include.lowest = TRUE)),
          !is.na(cut(100, cover_breaks, right = FALSE, include.lowest = TRUE)))

## ---- cut-na ----
stopifnot(is.na(cut(NA_real_, breaks)))

## ---- range-check ----
stems |>
  group_by(class_lowest_first) |>
  summarise(n = n(), smallest = min(dbh), largest = max(dbh))

stems |>
  group_by(class_catch_all) |>
  summarise(n = n(), smallest = min(dbh), largest = max(dbh))

stems |>
  group_by(cut_right) |>
  summarise(n = n(), smallest = min(dbh), largest = max(dbh))

protocol_ok <- with(stems, all(
  (size_class == "sapling" & dbh < 10) |
  (size_class == "pole"    & dbh >= 10 & dbh < 25) |
  (size_class == "mature"  & dbh >= 25 & dbh < 50) |
  (size_class == "large"   & dbh >= 50), na.rm = TRUE))
stopifnot(protocol_ok, sum(is.na(stems$size_class)) == sum(is.na(stems$dbh)))
pole_max <- max(stems$dbh[stems$class_lowest_first == "pole"], na.rm = TRUE)
sapling_max_cut <- max(stems$dbh[stems$cut_right == "sapling"], na.rm = TRUE)
