# Double constrained correspondence analysis in R
# https://tidyecology.com/posts/double-constrained-correspondence-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-11-04

## ---- data ----
set.seed(3120)
n_site <- 60; n_sp <- 40

elev_z <- as.numeric(scale(seq(-2, 2, length.out = n_site) + rnorm(n_site, 0, 0.25)))
sla_z  <- as.numeric(scale(rnorm(n_sp)))
seed_z <- as.numeric(scale(rnorm(n_sp)))
opt <- -1.2 * sla_z + rnorm(n_sp, 0, 0.4)

L <- matrix(0, n_site, n_sp)
for (j in 1:n_sp) L[, j] <- rpois(n_site, 25 * exp(-(elev_z - opt[j])^2 / (2 * 0.9^2)))
keep <- colSums(L) > 0
L <- L[, keep]; sla_z <- sla_z[keep]; seed_z <- seed_z[keep]
n_sp <- ncol(L)
Q <- cbind(SLA = sla_z, seed_mass = seed_z)
c(sites = n_site, species = n_sp)

## ---- machine ----
ca_weights <- function(L) {
  P <- L / sum(L)
  r <- rowSums(P); cw <- colSums(P)
  list(r = r, c = cw, Z = P / outer(r, cw) - 1, P = P)
}
wstd <- function(X, w) {
  Xc <- sweep(X, 2, colSums(X * w))
  sweep(Xc, 2, sqrt(colSums(Xc^2 * w)), "/")
}
msqrt_inv <- function(M) {          # inverse matrix square root
  e <- eigen(M, symmetric = TRUE)
  d <- 1 / sqrt(pmax(e$values, 1e-10))
  # d * t(e$vectors) is diag(d) %*% t(e$vectors) without building diag(d):
  # diag() of a length-1 vector returns an identity matrix, not a 1x1 matrix
  e$vectors %*% (d * t(e$vectors))
}

dcca <- function(R, L, Q) {
  ca <- ca_weights(L)
  Rw <- wstd(R, ca$r); Qw <- wstd(Q, ca$c)
  Zm <- t(Rw * ca$r) %*% ca$Z %*% (Qw * ca$c)      # the same cross table as RLQ
  CR <- t(Rw * ca$r) %*% Rw                        # weighted covariance of R
  CQ <- t(Qw * ca$c) %*% Qw                        # weighted covariance of Q
  Ar <- msqrt_inv(CR); Aq <- msqrt_inv(CQ)
  s <- svd(Ar %*% Zm %*% Aq)                       # THE step: whiten, then decompose
  list(d = s$d, u = Ar %*% s$u, v = Aq %*% s$v, ca = ca, Rw = Rw, Qw = Qw, Z = Zm)
}

## ---- check ----
fitR <- cbind(elevation = elev_z, slope = as.numeric(scale(rnorm(n_site))))
f <- dcca(fitR, L, Q)
sR <- as.numeric(f$Rw %*% f$u[, 1]); sQ <- as.numeric(f$Qw %*% f$v[, 1])
vR <- sum(sR^2 * f$ca$r); vQ <- sum(sQ^2 * f$ca$c)
cv <- sum((sR %o% sQ) * f$ca$P) - sum(sR * f$ca$r) * sum(sQ * f$ca$c)
p312_corr <- cv / sqrt(vR * vQ)
p312_d1 <- f$d[1]
p312_gap <- abs(p312_corr - p312_d1)
c(singular_value = p312_d1, correlation_of_scores = p312_corr, gap = p312_gap)

## ---- sweep-proxy ----
sweep_proxy <- function(nproxy, rho = 0.85) {
  set.seed(77)
  Rm <- cbind(elevation = elev_z)
  for (k in seq_len(nproxy))
    Rm <- cbind(Rm, as.numeric(scale(rho * elev_z + rnorm(n_site, 0, sqrt(1 - rho^2)))))
  pn <- if (nproxy > 0) paste0("proxy", seq_len(nproxy)) else character(0)
  colnames(Rm) <- c("elevation", pn)
  f <- dcca(Rm, L, Q)
  ld <- f$u[, 1] / sqrt(sum(f$u[, 1]^2))
  data.frame(proxies = nproxy, dcca_corr = f$d[1], elevation_share = abs(ld[1]))
}
sp <- do.call(rbind, lapply(0:4, sweep_proxy))
p312_sp <- sp
print(round(sp, 4), row.names = FALSE)

## ---- sweep-noise ----
sweep_noise <- function(p) {
  set.seed(900 + p)
  Rn <- matrix(rnorm(n_site * p), n_site)
  colnames(Rn) <- paste0("noise", seq_len(p))
  Rreal <- cbind(elevation = elev_z, Rn[, -1, drop = FALSE])
  data.frame(n_env_vars = p,
             with_real_driver = dcca(Rreal, L, Q)$d[1],
             noise_only = dcca(Rn, L, Q)$d[1])
}
ns <- do.call(rbind, lapply(c(1, 3, 6, 12, 20), sweep_noise))
p312_ns <- ns
p312_n1 <- ns$noise_only[1]; p312_n20 <- ns$noise_only[5]
p312_real <- ns$with_real_driver[5]
print(round(ns, 4), row.names = FALSE)

## ---- fig-noise ----
library(ggplot2)
theme_te <- function() {
  theme_minimal(base_size = 11) +
    theme(
          plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#dad9ca", linewidth = 0.3),
          plot.title = element_text(colour = "#16241d", face = "bold", size = 11),
          plot.subtitle = element_text(colour = "#5d6b61", size = 9),
          axis.title = element_text(colour = "#46604a", size = 9.5),
          axis.text = element_text(colour = "#5d6b61", size = 8.5),
          legend.position = "top", legend.title = element_blank(),
          legend.text = element_text(colour = "#2c3a31", size = 9))
}
dl <- rbind(
  data.frame(p = ns$n_env_vars, v = ns$with_real_driver, k = "elevation in the table"),
  data.frame(p = ns$n_env_vars, v = ns$noise_only, k = "noise variables only"))
ggplot(dl, aes(p, v, colour = k)) +
  geom_line(linewidth = 0.9) + geom_point(size = 2.4) +
  scale_colour_manual(values = c("elevation in the table" = "#275139",
                                 "noise variables only" = "#c9b458")) +
  scale_y_continuous(limits = c(0, 0.7)) +
  labs(title = "dc-CA manufactures correlation from noise",
       subtitle = "sixty sites, forty species, no ecology in the gold line at all",
       x = "number of environmental variables", y = "first canonical correlation") +
  theme_te()

## ---- perm ----
dcca_d1 <- function(R, L, Q) dcca(R, L, Q)$d[1]
perm_test <- function(R, L, Q, nperm = 199, seed = 1) {
  set.seed(seed)
  obs <- dcca_d1(R, L, Q)
  ps <- replicate(nperm, dcca_d1(R[sample(nrow(R)), , drop = FALSE], L, Q))
  pq <- replicate(nperm, dcca_d1(R, L, Q[sample(nrow(Q)), , drop = FALSE]))
  c(observed = obs,
    p_sites = (sum(ps >= obs) + 1) / (nperm + 1),
    p_species = (sum(pq >= obs) + 1) / (nperm + 1))
}
set.seed(920)
Rnoise <- matrix(rnorm(n_site * 20), n_site); colnames(Rnoise) <- paste0("noise", 1:20)
a <- perm_test(Rnoise, L, Q, seed = 1)
b <- perm_test(cbind(elevation = elev_z, Rnoise[, 1:2]), L, Q, seed = 2)
p312_a <- a; p312_b <- b
p312_a_max <- max(a["p_sites"], a["p_species"])
p312_b_max <- max(b["p_sites"], b["p_species"])
rbind(`noise only, 20 vars` = c(a, reported = p312_a_max),
      `elevation + 2 noise` = c(b, reported = p312_b_max))

## ---- nulls ----
set.seed(3)
nperm <- 199
obs_n <- dcca_d1(Rnoise, L, Q)
ns_site <- replicate(nperm, dcca_d1(Rnoise[sample(n_site), ], L, Q))
ns_sp   <- replicate(nperm, dcca_d1(Rnoise, L, Q[sample(n_sp), ]))
p312_null <- data.frame(
  null = c("shuffle sites", "shuffle species"),
  mean = c(mean(ns_site), mean(ns_sp)),
  sd = c(sd(ns_site), sd(ns_sp)),
  q95 = c(quantile(ns_site, 0.95), quantile(ns_sp, 0.95)))
p312_obs_n <- obs_n
print(round(p312_null[, -1], 4), row.names = FALSE)
