# Fitting growth curves with nls
# https://tidyecology.com/posts/fitting-growth-curves-nls/
#
# 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

## ---- sim ----
set.seed(4195)
Linf <- 60; k <- 0.25; t0 <- -0.5; sigma <- 3
ages <- rep(1:14, each = 6)
L    <- Linf * (1 - exp(-k * (ages - t0))) + rnorm(length(ages), 0, sigma)
d    <- data.frame(t = ages, L = L)

## ---- fit-fw ----
am  <- tapply(d$L, d$t, mean)
fw  <- lm(am[-1] ~ am[-length(am)])
k_fw    <- unname(-log(coef(fw)[2]))
Linf_fw <- unname(coef(fw)[1] / (1 - coef(fw)[2]))

## ---- fit-nls ----
fit <- nls(L ~ Linf * (1 - exp(-k * (t - t0))), data = d,
           start = list(Linf = max(L), k = 0.3, t0 = 0))
co  <- coef(fit)

## ---- fig-fit ----
library(ggplot2)
theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) +
    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),
          axis.title = element_text(colour = "#2c3a31"),
          axis.text  = element_text(colour = "#46604a"),
          plot.subtitle = element_text(colour = "#5d6b61"),
          legend.position = "top", legend.title = element_blank(),
          legend.text = element_text(colour = "#46604a"))
}
dy   <- d[d$t <= 6, ]
fity <- nls(L ~ Linf * (1 - exp(-k * (t - t0))), data = dy,
            start = list(Linf = 60, k = 0.25, t0 = 0),
            control = nls.control(warnOnly = TRUE))
gg <- data.frame(t = seq(0, 14, length.out = 200))
gg$full  <- predict(fit,  gg)
gg$young <- predict(fity, gg)
ggplot(d, aes(t, L)) +
  geom_point(aes(colour = ifelse(t <= 6, "age 6 or under", "older")),
             alpha = 0.7, size = 1.8) +
  geom_line(data = gg, aes(t, full),  colour = "#275139", linewidth = 1) +
  geom_line(data = gg, aes(t, young), colour = "#b5534e", linewidth = 1,
            linetype = "21") +
  geom_hline(yintercept = Linf, colour = "#16241d", linetype = "31") +
  scale_colour_manual(values = c("age 6 or under" = "#b5534e",
                                  "older" = "#93a87f")) +
  labs(x = "age (years)", y = "length (cm)", subtitle =
       "Solid green: fit to all fish; dashed red: fit from young fish only;\ndark dashed horizontal line: true asymptote") +
  theme_te()

## ---- mc ----
set.seed(20260811)
B  <- 2000
mc <- matrix(NA_real_, B, 4, dimnames = list(NULL, c("Lnls","knls","Lfw","kfw")))
for (b in seq_len(B)) {
  Lb <- Linf * (1 - exp(-k * (ages - t0))) + rnorm(length(ages), 0, sigma)
  db <- data.frame(t = ages, L = Lb)
  fb <- try(nls(L ~ Linf * (1 - exp(-k * (t - t0))), data = db,
                start = list(Linf = 60, k = 0.25, t0 = 0),
                control = nls.control(warnOnly = TRUE)), silent = TRUE)
  if (!inherits(fb, "try-error") && fb$convInfo$isConv) {
    mc[b, 1] <- coef(fb)["Linf"]; mc[b, 2] <- coef(fb)["k"] }
  amb <- tapply(db$L, db$t, mean)
  sl  <- coef(lm(amb[-1] ~ amb[-length(amb)]))[2]
  if (sl > 0 && sl < 1) { mc[b, 3] <- coef(lm(amb[-1] ~ amb[-length(amb)]))[1] / (1 - sl)
                          mc[b, 4] <- -log(sl) }
}
mc <- mc[complete.cases(mc), ]
eff_L <- sd(mc[, 3]) / sd(mc[, 1]); eff_k <- sd(mc[, 4]) / sd(mc[, 2])

## ---- models ----
fg <- nls(L ~ Linf * exp(-b * exp(-k * t)), data = d,
          start = list(Linf = max(L), b = 2, k = 0.3))
fl <- nls(L ~ Linf / (1 + exp(-k * (t - tm))), data = d,
          start = list(Linf = max(L), k = 0.4, tm = 3))
aic <- c(vonBert = AIC(fit), Gompertz = AIC(fg), logistic = AIC(fl))

## ---- fig-tradeoff ----
td <- data.frame(Linf = mc[, 1], kk = mc[, 2])
ggplot(td, aes(Linf, kk)) +
  geom_point(colour = "#275139", alpha = 0.15, size = 0.8) +
  geom_point(data = data.frame(Linf = Linf, kk = k), aes(Linf, kk),
             colour = "#b5534e", shape = 4, size = 2.8, stroke = 1.3) +
  labs(x = "estimated asymptote", y = "estimated growth coefficient",
       subtitle = "Each dot is one simulated fit; the cross is the truth") +
  theme_te()

## ---- young ----
se_Ly  <- summary(fity)$coefficients["Linf", "Std. Error"]
wald_Ly <- coef(fity)["Linf"] + c(-1, 1) * 1.96 * se_Ly
prof_Ly <- suppressMessages(confint(fity, "Linf"))
