# Association indices for social networks
# https://tidyecology.com/posts/association-indices-social-networks/
#
# 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

## ---- setup ----
library(ggplot2)
theme_set(theme_minimal(base_size = 12) +
  theme(plot.background = element_rect(fill = "#f5f4ee", colour = NA),
        panel.background = element_rect(fill = "#f5f4ee", colour = NA),
        panel.grid.minor = element_blank()))
knitr::opts_chunk$set(dev.args = list(bg = "#f5f4ee"))

## ---- data ----
obs <- data.frame(
  period = c(1,1, 2,2, 3,3, 4,4,4, 5,5, 6,6, 7, 8,8, 9,9,9, 10,10,
             11,11, 12, 13,13, 14,14, 15),
  group  = c(1,1, 1,1, 1,1, 1,1,2, 1,1, 1,1, 1, 1,1, 1,1,2, 1,1,
             1,1, 1, 1,1, 1,1, 1),
  id     = c("A","B", "A","B", "A","B", "A","B","C", "A","C", "B","C", "A",
             "C","D", "A","B","C", "D","E", "D","E", "E", "E","F", "E","F","F")
)
ids <- sort(unique(obs$id))
n <- length(ids)

## ---- counts ----
counts <- function(i, j) {
  x <- yab <- ya <- yb <- 0L
  for (p in unique(obs$period)) {
    sub <- obs[obs$period == p, ]
    gi <- sub$group[sub$id == i]
    gj <- sub$group[sub$id == j]
    seen_i <- length(gi) > 0
    seen_j <- length(gj) > 0
    if (seen_i && seen_j) {
      if (any(gi %in% gj)) x <- x + 1L else yab <- yab + 1L
    } else if (seen_i) ya <- ya + 1L
    else if (seen_j) yb <- yb + 1L
  }
  c(x = x, yab = yab, ya = ya, yb = yb)
}
counts("A", "B")

## ---- indices ----
sri <- hwi <- matrix(0, n, n, dimnames = list(ids, ids))
tab <- list()
for (a in 1:(n-1)) for (b in (a+1):n) {
  cc <- counts(ids[a], ids[b])
  s <- cc["x"] / (cc["x"] + cc["yab"] + cc["ya"] + cc["yb"])
  h <- cc["x"] / (cc["x"] + cc["yab"] + 0.5*(cc["ya"] + cc["yb"]))
  sri[ids[a], ids[b]] <- sri[ids[b], ids[a]] <- s
  hwi[ids[a], ids[b]] <- hwi[ids[b], ids[a]] <- h
  tab[[length(tab)+1]] <- data.frame(i = ids[a], j = ids[b],
      x = cc["x"], yab = cc["yab"], ya = cc["ya"], yb = cc["yb"],
      SRI = round(s, 3), HWI = round(h, 3), diff = round(h - s, 3))
}
tab <- do.call(rbind, tab); rownames(tab) <- NULL
tab[order(-tab$SRI), ]

## ---- fig-heatmap ----
long <- expand.grid(i = ids, j = ids)
long$sri <- mapply(function(a, b) sri[a, b], long$i, long$j)
ggplot(long, aes(i, j, fill = sri)) +
  geom_tile(colour = "#cfcdc0", linewidth = 0.6) +
  scale_fill_gradient(low = "#e6e4d8", high = "#2b5d34", name = "SRI") +
  coord_equal() +
  labs(x = NULL, y = NULL,
       title = "Pairwise association (simple ratio index)")

## ---- fig-divergence ----
ggplot(tab, aes(SRI, HWI)) +
  geom_abline(slope = 1, intercept = 0, linetype = "dashed", colour = "grey60") +
  geom_point(aes(size = ya + yb), colour = "#2b5d34", alpha = 0.8) +
  scale_size_continuous(name = "seen singly\n(ya + yb)", range = c(2, 6)) +
  coord_equal(xlim = c(0, 0.85), ylim = c(0, 0.85)) +
  labs(title = "The gap is widest at middling association",
       x = "simple ratio index", y = "half-weight index")

## ---- maxgap ----
c(max_HWI_minus_SRI = round(max(abs(tab$diff)), 3),
  edges_present = sum(sri[upper.tri(sri)] > 0),
  dyads_total = n * (n - 1) / 2)
