# Checking a CNDD analysis
# https://tidyecology.com/posts/checking-a-cndd-analysis/
#
# 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-30

## ---- setup ----
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE,
                      dev = "png", dpi = 120, fig.path = "figures/",
                      fig.width = 7, fig.height = 4.4)
library(ggplot2)
theme_te <- theme_minimal(base_size = 12) +
  theme(panel.background = element_rect(fill = "#f5f4ee", colour = NA),
        plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
        panel.grid.minor = element_blank(),
        plot.title = element_text(face = "bold", size = 12))
theme_set(theme_te)
col_naive <- "#b5651d"; col_adj <- "#3a6b52"; col_ref <- "#555555"

set.seed(418); n <- 1500
habitat <- rnorm(n)
conspec <- 2*habitat + rnorm(n, 0, 1)           # species clusters in good habitat
true_cndd <- -0.5
surv <- rbinom(n, 1, plogis(1.0 + true_cndd*conspec + 1.2*habitat))
b_naive <- coef(glm(surv ~ conspec, family = binomial))["conspec"]
b_adj   <- coef(glm(surv ~ conspec + habitat, family = binomial))["conspec"]

## ---- confound ----
set.seed(418); n <- 1500
habitat <- rnorm(n)
conspec <- 2*habitat + rnorm(n, 0, 1)                 # clusters in good habitat: conspec tracks habitat
surv <- rbinom(n, 1, plogis(1.0 - 0.5*conspec + 1.2*habitat))   # true CNDD is negative
c(naive = coef(glm(surv ~ conspec, family = binomial))["conspec"],
  habitat_adjusted = coef(glm(surv ~ conspec + habitat, family = binomial))["conspec"])

## ---- fig-confound ----
dd <- data.frame(conspec = conspec, surv = surv,
                 band = cut(habitat, quantile(habitat, 0:4/4), include.lowest = TRUE, labels = paste("habitat", 1:4)))
ggplot(dd, aes(conspec, surv)) +
  geom_smooth(method = "glm", method.args = list(family = binomial), se = FALSE, colour = col_naive, linewidth = 1.1) +
  geom_smooth(aes(group = band), method = "glm", method.args = list(family = binomial), se = FALSE, colour = col_adj, linewidth = 0.6) +
  labs(x = "Conspecific density", y = "Survival",
       title = "Flat overall, declining within each habitat band")

## ---- fig-coef ----
dc <- data.frame(est = factor(c("true","naive","habitat-adjusted"), levels = c("true","naive","habitat-adjusted")),
                 val = c(-0.5, b_naive, b_adj))
ggplot(dc, aes(est, val, fill = est)) +
  geom_col(width = 0.6) +
  geom_hline(yintercept = 0, colour = col_ref, linewidth = 0.4) +
  scale_fill_manual(values = c("true" = col_ref, "naive" = col_naive, "habitat-adjusted" = col_adj), guide = "none") +
  labs(x = NULL, y = "Conspecific coefficient", title = "Ignoring habitat erases the density dependence")
