# Resource selection functions in R
# https://tidyecology.com/posts/resource-selection-functions/
#
# 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-10-07

## ---- setup ----
te_ink <- "#16241d"; te_body <- "#2c3a31"; te_forest <- "#275139"
te_label <- "#46604a"; te_sage <- "#93a87f"; te_paper <- "#f5f4ee"
te_line <- "#dad9ca"; te_faint <- "#5d6b61"; te_gold <- "#cda23f"; te_red <- "#b5534e"
theme_te <- function(base_size = 12) {
  ggplot2::theme_minimal(base_size = base_size) +
    ggplot2::theme(
      text = ggplot2::element_text(colour = te_body),
      plot.title = ggplot2::element_text(colour = te_ink, face = "bold"),
      plot.subtitle = ggplot2::element_text(colour = te_faint),
      axis.title = ggplot2::element_text(colour = te_label),
      axis.text = ggplot2::element_text(colour = te_faint),
      panel.grid.major = ggplot2::element_line(colour = te_line, linewidth = 0.3),
      panel.grid.minor = ggplot2::element_blank(),
      plot.background = ggplot2::element_rect(fill = te_paper, colour = NA),
      panel.background = ggplot2::element_rect(fill = te_paper, colour = NA),
      legend.key = ggplot2::element_blank(),
      legend.title = ggplot2::element_text(colour = te_label),
      strip.text = ggplot2::element_text(colour = te_ink, face = "bold"))
}

## ---- data ----
library(ggplot2); library(dplyr); library(tidyr)

set.seed(3607)
ncell <- 6000
x1 <- rnorm(ncell)
x2 <- 0.6 * x1 + sqrt(1 - 0.6^2) * rnorm(ncell)   # correlated with x1, no direct effect
b1 <- 1.2; b2 <- 0                                # true selection: x1 only
w <- exp(b1 * x1 + b2 * x2)                       # RSF, exponential form

n_used <- 300
used_id <- sample(ncell, n_used, prob = w)

make_data <- function(k) {
  av_id <- sample(ncell, k * n_used)
  rbind(data.frame(used = 1, x1 = x1[used_id], x2 = x2[used_id]),
        data.frame(used = 0, x1 = x1[av_id],  x2 = x2[av_id]))
}
d <- make_data(5)
round(cor(x1, x2), 2)

## ---- selratio ----
d$x2class <- cut(d$x2, breaks = quantile(d$x2, 0:4 / 4), include.lowest = TRUE, labels = 1:4)
sr <- d %>% group_by(x2class) %>%
  summarise(used_p = mean(used == 1), avail_p = mean(used == 0), .groups = "drop")
sr$ratio <- (sr$used_p / sum(sr$used_p)) / (sr$avail_p / sum(sr$avail_p))
round(sr$ratio, 2)

## ---- rsf ----
m_x2   <- glm(used ~ x2, family = binomial, data = d)
m_both <- glm(used ~ x1 + x2, family = binomial, data = d)
round(c(x2_alone = coef(m_x2)["x2"],
        both_x1 = coef(m_both)["x1"], both_x2 = coef(m_both)["x2"]), 3)

## ---- fig-densities ----
dl <- d %>% select(used, x1, x2) %>%
  pivot_longer(c(x1, x2), names_to = "covariate", values_to = "value") %>%
  mutate(group = ifelse(used == 1, "used", "available"))
ggplot(dl, aes(value, colour = group, fill = group)) +
  geom_density(alpha = 0.25, linewidth = 0.8) +
  facet_wrap(~covariate, labeller = as_labeller(c(x1 = "x1 (true driver)", x2 = "x2 (correlated only)"))) +
  scale_colour_manual(values = c(used = te_forest, available = te_faint), name = NULL) +
  scale_fill_manual(values = c(used = te_forest, available = te_faint), name = NULL) +
  labs(title = "Used versus available covariate distributions",
       x = "covariate value (standardised)", y = "density") +
  theme_te(13)

## ---- relscale ----
mult <- c(1, 3, 10, 20)
rs <- lapply(mult, function(k) {
  set.seed(1000 + k)
  m <- glm(used ~ x1 + x2, family = binomial, data = make_data(k))
  data.frame(mult = k, intercept = coef(m)[1], x1 = coef(m)["x1"], x2 = coef(m)["x2"])
})
rs <- do.call(rbind, rs)
round(rs, 3)

## ---- fig-relscale ----
rl <- rs %>% pivot_longer(c(intercept, x1, x2), names_to = "term", values_to = "estimate") %>%
  mutate(term = factor(term, levels = c("intercept", "x1", "x2"),
                       labels = c("intercept", "slope x1", "slope x2")))
ggplot(rl, aes(mult, estimate)) +
  geom_line(colour = te_forest, linewidth = 0.8) + geom_point(colour = te_forest, size = 2) +
  facet_wrap(~term) +
  labs(title = "Only the intercept depends on the available sample size",
       x = "available points per used point", y = "coefficient") +
  theme_te(13)

## ---- rss ----
round(exp(coef(m_both)["x1"] * 1), 2)
