# Back-transforming a log-scale model
# https://tidyecology.com/posts/back-transforming-a-log-model/
#
# 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-14

## ---- setup ----
library(ggplot2)

te_paper  <- "#f5f4ee"
te_ink    <- "#16241d"
te_body   <- "#2c3a31"
te_forest <- "#275139"
te_rust   <- "#b5534e"
te_gold   <- "#c9b458"
te_line   <- "#dad9ca"

theme_datasheet <- function() {
  theme_minimal(base_size = 12) +
    theme(plot.background  = element_rect(fill = te_paper, colour = NA),
          panel.background = element_rect(fill = te_paper, colour = NA),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          text             = element_text(colour = te_body),
          plot.title       = element_text(colour = te_ink, face = "bold"),
          axis.text        = element_text(colour = te_body))
}

set.seed(8213)
n_stem <- 400
a_true <- 0.088
b_true <- 2.42
s_true <- 0.45                      # residual SD on the log scale

dbh  <- exp(rnorm(n_stem, log(24), 0.5))
mass <- a_true * dbh^b_true * exp(rnorm(n_stem, 0, s_true))

fit   <- lm(log(mass) ~ log(dbh))
s_hat <- summary(fit)$sigma
round(c(intercept = unname(coef(fit)[1]), slope = unname(coef(fit)[2]),
        resid_sd = s_hat), 3)

## ---- median-mean ----
naive <- exp(fitted(fit))                       # exponentiated fitted line
share_below <- mean(mass < naive)
tot_true    <- sum(mass)
tot_naive   <- sum(naive)
round(c(share_below_line = share_below,
        true_total_t     = tot_true / 1000,
        naive_total_t    = tot_naive / 1000,
        shortfall_pct    = 100 * (1 - tot_naive / tot_true)), 3)

## ---- fig-median ----
ratio <- mass / naive
dbin  <- cut(dbh, breaks = quantile(dbh, seq(0, 1, length.out = 11)),
             include.lowest = TRUE)
bin_dbh  <- tapply(dbh, dbin, mean)
bin_med  <- tapply(ratio, dbin, median)
bin_mean <- tapply(ratio, dbin, mean)
binned <- rbind(
  data.frame(dbh = bin_dbh, y = bin_med,  stat = "bin median"),
  data.frame(dbh = bin_dbh, y = bin_mean, stat = "bin mean"))

ggplot(binned, aes(dbh, y)) +
  geom_point(data = data.frame(dbh = dbh, y = ratio), colour = te_body,
             alpha = 0.22, size = 1.3) +
  geom_hline(yintercept = 1, colour = te_forest, linetype = "dashed") +
  geom_hline(yintercept = exp(s_hat^2 / 2), colour = te_rust,
             linetype = "dashed") +
  geom_point(aes(colour = stat, shape = stat), size = 3) +
  scale_colour_manual(values = c(te_rust, te_forest)) +
  scale_x_log10() +
  scale_y_log10() +
  labs(x = "stem diameter (cm, log spaced)",
       y = "observed mass / back-transformed prediction",
       colour = NULL, shape = NULL,
       title = "The line is a median wherever you look") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- sigma-grid ----
set.seed(4021)
inv_dbh <- exp(rnorm(2000, log(24), 0.5))     # the standing inventory
inv_lgd <- log(inv_dbh)
inv_mu  <- a_true * inv_dbh^b_true            # expected mass before the error

true_mult <- function(s, shape = "normal") {  # E[exp(residual)]
  if (shape == "normal") return(exp(s^2 / 2))
  k <- 0.5
  a <- s / sqrt(k)
  if (shape == "right-skewed") exp(-a * k) * (1 - a)^(-k)
  else                         exp( a * k) * (1 + a)^(-k)
}

one_stand <- function(n, s) {
  d <- exp(rnorm(n, log(24), 0.5))
  y <- a_true * d^b_true * exp(rnorm(n, 0, s))
  b <- unname(coef(lm(log(y) ~ log(d))))
  sum(exp(b[1] + b[2] * inv_lgd)) / (sum(inv_mu) * true_mult(s))
}

set.seed(51)
n_rep  <- 4000
design <- expand.grid(s = seq(0.1, 0.8, by = 0.1), n = c(40, 200, 2000))
cells  <- mapply(function(n, s) {
  v <- replicate(n_rep, one_stand(n, s))
  c(100 * (1 - mean(v)), 100 * sd(v) / sqrt(n_rep))
}, design$n, design$s)
design$shortfall <- cells[1, ]
design$mc_se     <- cells[2, ]

with(design, round(tapply(shortfall, list(s, n), mean), 2))

row_spread <- max(tapply(design$shortfall, design$s, function(v) diff(range(v))))
round(c(widest_gap_across_n  = row_spread,
        range_across_sigma   = diff(range(design$shortfall)),
        mc_se_smallest_sigma = max(design$mc_se[design$s == 0.1])), 3)

## ---- fig-sigma ----
theory <- data.frame(s = seq(0.1, 0.8, length.out = 200))
theory$shortfall <- 100 * (1 - exp(-theory$s^2 / 2))

design$stems <- factor(design$n, labels = c("40 stems", "200 stems",
                                            "2000 stems"))

ggplot(design, aes(s, shortfall)) +
  geom_line(data = theory, colour = te_body, linewidth = 1.1, alpha = 0.5) +
  geom_point(aes(colour = stems, shape = stems), size = 2.6) +
  scale_colour_manual(values = c(te_forest, te_rust, te_gold)) +
  labs(x = "residual standard deviation on the log scale",
       y = "shortfall in the inventory total (per cent)",
       colour = NULL, shape = NULL,
       title = "The bias tracks the scatter, not the sample") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- corrections ----
cf_lnorm  <- exp(s_hat^2 / 2)
cf_smear  <- mean(exp(residuals(fit)))
round(c(lognormal_factor = cf_lnorm,
        smearing_factor  = cf_smear,
        lognormal_total_t = tot_naive * cf_lnorm / 1000,
        smearing_total_t  = tot_naive * cf_smear / 1000,
        true_total_t      = tot_true / 1000), 4)

## ---- spread ----
one_replicate <- function() {
  d <- exp(rnorm(n_stem, log(24), 0.5))
  y <- a_true * d^b_true * exp(rnorm(n_stem, 0, s_true))
  f <- lm(log(y) ~ log(d))
  p <- sum(exp(fitted(f)))
  c(naive     = p / sum(y),
    lognormal = p * exp(summary(f)$sigma^2 / 2) / sum(y),
    smearing  = p * mean(exp(residuals(f))) / sum(y))
}

set.seed(4471)
err <- 100 * (replicate(4000, one_replicate()) - 1)
round(rbind(mean_error_pct = rowMeans(err),
            lower_2.5      = apply(err, 1, quantile, 0.025),
            upper_97.5     = apply(err, 1, quantile, 0.975)), 2)
round(c(share_within_1_pc = mean(abs(err["lognormal", ]) < 1)), 3)

## ---- shapes ----
draw_resid <- function(n, s, shape) {
  if (shape == "normal") return(rnorm(n, 0, s))
  k <- 0.5
  a <- s / sqrt(k)                       # so that the SD is s in every case
  g <- a * (rgamma(n, shape = k, rate = 1) - k)
  if (shape == "right-skewed") g else -g
}

one_shape <- function(shape) {
  d <- exp(rnorm(300, log(24), 0.5))
  y <- a_true * d^b_true * exp(draw_resid(300, s_true, shape))
  f <- lm(log(y) ~ log(d))
  b <- unname(coef(f))
  p <- sum(exp(b[1] + b[2] * inv_lgd))
  truth <- sum(inv_mu) * true_mult(s_true, shape)
  c(naive      = p / truth,
    parametric = p * exp(summary(f)$sigma^2 / 2) / truth,
    smearing   = p * mean(exp(residuals(f))) / truth)
}

set.seed(9902)
shapes <- c("normal", "right-skewed", "left-skewed")
sims <- lapply(shapes, function(sh) replicate(2000, one_shape(sh)))
names(sims) <- shapes
res <- t(vapply(sims, rowMeans, numeric(3)))
round(res, 3)

## ---- fig-shapes ----
long <- data.frame(shape  = rep(rownames(res), times = 3),
                   method = rep(colnames(res), each = 3),
                   ratio  = as.vector(res))
long$shape  <- factor(long$shape, levels = rev(shapes))
long$method <- factor(long$method,
                      levels = c("naive", "parametric", "smearing"))

ggplot(long, aes(ratio, shape, colour = method, shape = method)) +
  geom_vline(xintercept = 1, linetype = "dashed", colour = te_body) +
  geom_point(size = 3.4, alpha = 0.9) +
  scale_colour_manual(values = c(te_body, te_rust, te_forest)) +
  labs(x = "predicted inventory total / true inventory total", y = NULL,
       colour = NULL, shape = NULL,
       title = "Same spread, different shape, different answer") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- glm-contrast ----
set.seed(707)
d2  <- exp(rnorm(500, log(24), 0.5))
mu2 <- a_true * d2^b_true
y2  <- rgamma(500, shape = 5, rate = 5 / mu2)     # mean mu2, right-skewed

m_lm  <- lm(log(y2) ~ log(d2))
m_glm <- glm(y2 ~ log(d2), family = Gamma(link = "log"))

round(c(expected_total_t = sum(mu2) / 1000,
        lm_naive_t       = sum(exp(fitted(m_lm))) / 1000,
        lm_smeared_t     = sum(exp(fitted(m_lm))) *
                             mean(exp(residuals(m_lm))) / 1000,
        glm_total_t      = sum(fitted(m_glm)) / 1000), 2)
