# R code for Bayesian negative binomial regression
# Horseshoe crabs example: Section 3.3 of Agresti
# Regress Y = number of satellites on X = shell width
# Read in data
rm(list=ls()); set.seed(20210403);
# You’ll need an internet connection for this to work
filename <- "http://www.stat.ufl.edu/~aa/cat/data/Crabs.dat"
Crabs <- read.table(file=filename, header=T); rm(filename);
Crabs # The Data!
dim(Crabs); names(Crabs); # We'll only use sat & width for now
# Model fitting -- we will do negative binomial regression now, which
# is a useful model for over-dispersed count data
library(rstan)
stan_model <- "
data{
int
int
vector [n] x;
}
parameters{
real alpha;
real beta;
real
}
transformed parameters{
vector[n] lambda;
lambda = exp(alpha + beta*x);
}
model{
m ~ gamma(.01, .01);
alpha ~ normal(0, 100);
beta ~ normal(0, 100);
y ~ neg_binomial_2(lambda, m) ;
}
”
n <- dim(Crabs)[1]; y <- Crabs$sat; x <- Crabs$width; data <- list(n=n, y=y, x=x) fit <- stan(model_code=stan_model, data=data, iter=2000, chains=5) sims <- extract(fit); names(sims); Results <- summary(fit)$summary; Results <- Results[1:3, ]; round(Results, 2);