# Dendritic spine density: a Poisson mixed model of all segments with log(length) as an offset and random effects for
# mouse, for neuron within mouse and for segment (extra scatter between segments beyond Poisson), the alternative to
# analysis C. Mouse and neuron IDs are combined with genotype so that reused labels cannot merge animals.
# R 4.3.3 with lme4. R only.
suppressPackageStartupMessages(library(lme4))
d <- read.csv("spines.csv"); d$mouse <- paste(d$genotype, d$mouse); d$cell <- paste(d$mouse, d$neuron); d$seg <- seq_len(nrow(d))
fit <- glmer(spines ~ genotype + offset(log(length_um)) + (1 | mouse) + (1 | cell) + (1 | seg), family = poisson, data = d)
s <- coef(summary(fit))["genotypewild-type", ]; b <- -s[["Estimate"]]; se <- s[["Std. Error"]]
cat(sprintf("Poisson mixed model (mouse, neuron and segment random effects): knockout / wild-type rate ratio %.2f (95%% Wald CI %.2f to %.2f), p = %s\n",
            exp(b), exp(b - 1.96 * se), exp(b + 1.96 * se), formatC(signif(s[["Pr(>|z|)"]], 2), format = "g")))
