library(rstan)
options(mc.cores = parallel::detectCores())
rstan_options(auto_write = TRUE)
(Riefer et al., 2002)
data(MemoryDeficits, package = "psychotools")
dat <- # multinomial counts, by subject and trial
subset(MemoryDeficits, trial %in% c(1, 2, 6) & group == "AlcCtl") |>
droplevels()
dat1 <- # aggregate counts by trial
aggregate(cbind(E1, E2, E3, E4) ~ trial + group, dat, sum) |>
print()
## trial group E1 E2 E3 E4
## 1 1 AlcCtl 45 24 97 254
## 2 2 AlcCtl 106 41 107 166
## 3 6 AlcCtl 243 64 65 48
dat2 <- # categorical responses, long format
cbind(dat[, c("ID", "trial")],
t(apply(dat[, c("E1", "E2", "E3", "E4")], 1, rep, x = 1:4))) |>
reshape(direction = "long", varying = 3:22, v.names = "ycat") |>
sort_by(~ ID + trial)
datlist <- list(
switch_multinom = 1,
y = dat1[1, c("E1", "E2", "E3", "E4")] |> unlist()
)
datlist$ycat <- rep(1:4, datlist$y)
datlist$N <- sum(datlist$y)
s <- "
functions {
vector rdirichlet_rng(vector alpha) {
return dirichlet_rng(alpha);
}
}
data {
int<lower=0, upper=1> switch_multinom; // multinomial or categorical?
array[4] int<lower=0> y; // multinomial counts
int<lower=1> N;
array[N] int<lower=1, upper=4> ycat; // categorical responses
}
parameters {
simplex[4] theta;
}
model {
theta ~ dirichlet([2, 2, 2, 2]');
if (switch_multinom) {
y ~ multinomial(theta);
} else {
ycat ~ categorical(theta);
}
}
"
m <- stan(model_code = s, data = datlist)
print(m, pars = "theta", probs = c(.025, .975))
## Inference for Stan model: anon_model.
## 4 chains, each with iter=2000; warmup=1000; thin=1;
## post-warmup draws per chain=1000, total post-warmup draws=4000.
##
## mean se_mean sd 2.5% 97.5% n_eff Rhat
## theta[1] 0.11 0 0.01 0.08 0.14 4310 1
## theta[2] 0.06 0 0.01 0.04 0.09 4651 1
## theta[3] 0.23 0 0.02 0.19 0.27 4066 1
## theta[4] 0.60 0 0.02 0.55 0.64 4230 1
##
## Samples were drawn using NUTS(diag_e) at Mon Nov 10 11:47:46 2025.
## For each parameter, n_eff is a crude measure of effective sample size,
## and Rhat is the potential scale reduction factor on split chains (at
## convergence, Rhat=1).
stanc(model_code = s) |> expose_stan_functions()
rdirichlet_rng(c(2, 2, 2, 2))
## [1] 0.1186110 0.4738062 0.2329962 0.1745866
# /r -- E1
# c
# / \1-r -- E4 c: cluster storage
# / r: cluster retrieval
# \ /u -- E2 u: non-clustered storage/retrieval
# \ u
# \ / \1-u -- E3
# 1-c
# \ /u -- E3
# 1-u
# \1-u -- E4
s <- "
data {
array[4] int<lower=0> y;
}
parameters {
real<lower=0, upper=1> c; // cluster storage
real<lower=0, upper=1> r; // cluster retrieval
real<lower=0, upper=1> u; // unique storage/retrieval
}
model {
[c, r, u]' ~ beta(2, 2);
y ~ multinomial(
[c*r, // dog, cat
(1 - c)*u^2, // dog, ..., cat
2*(1 - c)*u*(1 - u), // only dog or only cat
c*(1 - r) + (1 - c)*(1 - u)^2]' // neither dog nor cat
);
}
"
m <- stan(model_code = s, data = datlist)
print(m, pars = c("c", "r", "u"), probs = c(.025, .975))
## Inference for Stan model: anon_model.
## 4 chains, each with iter=2000; warmup=1000; thin=1;
## post-warmup draws per chain=1000, total post-warmup draws=4000.
##
## mean se_mean sd 2.5% 97.5% n_eff Rhat
## c 0.45 0 0.08 0.26 0.59 778 1
## r 0.25 0 0.07 0.17 0.43 692 1
## u 0.32 0 0.05 0.23 0.42 864 1
##
## Samples were drawn using NUTS(diag_e) at Mon Nov 10 10:53:19 2025.
## For each parameter, n_eff is a crude measure of effective sample size,
## and Rhat is the potential scale reduction factor on split chains (at
## convergence, Rhat=1).
s <- "
#include ../pcat.stan
data {
array[4] int<lower=0> y;
}
parameters {
vector<lower=0, upper=1>[3] theta; // [c, r, u]'
}
model {
theta ~ beta(2, 2);
y ~ multinomial(pcat(theta));
}
"
m <- stan(model_code = s, data = datlist)
print(m, pars = "theta", probs = c(.025, .975))
## Inference for Stan model: anon_model.
## 4 chains, each with iter=2000; warmup=1000; thin=1;
## post-warmup draws per chain=1000, total post-warmup draws=4000.
##
## mean se_mean sd 2.5% 97.5% n_eff Rhat
## theta[1] 0.45 0 0.08 0.27 0.58 710 1.00
## theta[2] 0.25 0 0.06 0.17 0.41 668 1.01
## theta[3] 0.32 0 0.05 0.23 0.42 802 1.00
##
## Samples were drawn using NUTS(diag_e) at Mon Nov 10 10:55:49 2025.
## For each parameter, n_eff is a crude measure of effective sample size,
## and Rhat is the potential scale reduction factor on split chains (at
## convergence, Rhat=1).
datlist <- list(
y = dat[, c("E1", "E2", "E3", "E4")],
trial = factor(dat$trial) |> as.numeric(),
ntrial = unique(dat$trial) |> length(),
idx = matrix(1:9, 3, 3, byrow = TRUE),
ntheta = 9,
N = nrow(dat),
ycat = dat2$ycat,
trial2 = factor(dat2$trial) |> as.numeric(),
N2 = nrow(dat2)
)
s <- "
#include ../pcat.stan
data {
int<lower=1> N; // number of multinomial counts
int<lower=1> ntrial; // number of trials
int<lower=1> ntheta; // number of parameters
array[N] int<lower=1> trial; // trial id
array[ntrial, 3] int<lower=1> idx; // parameter id
array[N, 4] int<lower=0> y; // by-subj observations x resp cat
int<lower=1> N2; // number of categorical responses
array[N2] int<lower=1> trial2; // trial id (categorical obs.)
array[N2] int<lower=1, upper=4> ycat; // categorical responses
}
parameters {
vector<lower=0, upper=1>[ntheta] theta; // c1, r1, u1, ..., c6, r6, u6
}
model {
theta ~ beta(2, 2);
for (i in 1:N) {
y[i] ~ multinomial(pcat(theta[idx[trial[i]]]));
}
// for (i in 1:N2) {
// ycat[i] ~ categorical(pcat(theta[idx[trial2[i]]]));
// }
}
generated quantities {
vector[N2] log_lik;
for (i in 1:N2) {
log_lik[i] = categorical_lpmf(ycat[i] | pcat(theta[idx[trial2[i]]]));
}
}
"
m1 <- stan(model_code = s, data = datlist)
## recompiling to avoid crashing R session
print(m1, pars = "theta", probs = c(.025, .975))
## Inference for Stan model: anon_model.
## 4 chains, each with iter=2000; warmup=1000; thin=1;
## post-warmup draws per chain=1000, total post-warmup draws=4000.
##
## mean se_mean sd 2.5% 97.5% n_eff Rhat
## theta[1] 0.45 0 0.08 0.26 0.58 1491 1.00
## theta[2] 0.25 0 0.07 0.17 0.43 1265 1.01
## theta[3] 0.32 0 0.05 0.23 0.42 1829 1.00
## theta[4] 0.47 0 0.05 0.36 0.57 2034 1.00
## theta[5] 0.54 0 0.07 0.43 0.71 1754 1.00
## theta[6] 0.43 0 0.04 0.34 0.52 2406 1.00
## theta[7] 0.65 0 0.03 0.60 0.70 2361 1.00
## theta[8] 0.88 0 0.03 0.83 0.94 2212 1.00
## theta[9] 0.66 0 0.04 0.58 0.73 2388 1.00
##
## Samples were drawn using NUTS(diag_e) at Mon Nov 10 10:58:38 2025.
## For each parameter, n_eff is a crude measure of effective sample size,
## and Rhat is the potential scale reduction factor on split chains (at
## convergence, Rhat=1).
extract(m1)$theta |>
colMeans() |>
matrix(3, 3, dimnames = list(c("c", "r", "u"), trial = c(1, 2, 6)))
## trial
## 1 2 6
## c 0.4486753 0.4713580 0.6514961
## r 0.2541511 0.5407987 0.8813738
## u 0.3206806 0.4301073 0.6603458
datlist$idx <- rbind(1:3, c(1, 4:5), c(1, 6:7)) # single c for all trials
datlist$ntheta <- as.vector(datlist$idx) |> # 9 - 2
unique() |>
length()
m2 <- stan(model_code = s, data = datlist)
print(m2, pars = "theta", probs = c(.025, .975))
## Inference for Stan model: anon_model.
## 4 chains, each with iter=2000; warmup=1000; thin=1;
## post-warmup draws per chain=1000, total post-warmup draws=4000.
##
## mean se_mean sd 2.5% 97.5% n_eff Rhat
## theta[1] 0.58 0 0.02 0.53 0.62 2675 1
## theta[2] 0.20 0 0.03 0.15 0.25 4367 1
## theta[3] 0.39 0 0.03 0.33 0.46 3469 1
## theta[4] 0.46 0 0.04 0.39 0.54 3667 1
## theta[5] 0.50 0 0.03 0.43 0.56 3871 1
## theta[6] 0.91 0 0.03 0.86 0.97 2425 1
## theta[7] 0.62 0 0.04 0.55 0.70 2800 1
##
## Samples were drawn using NUTS(diag_e) at Mon Nov 10 10:59:07 2025.
## For each parameter, n_eff is a crude measure of effective sample size,
## and Rhat is the potential scale reduction factor on split chains (at
## convergence, Rhat=1).
extract(m2)$theta |>
colMeans() |>
_[t(datlist$idx)] |>
matrix(3, 3, dimnames = list(c("c", "r", "u"), trial = c(1, 2, 6)))
## trial
## 1 2 6
## c 0.5777638 0.5777638 0.5777638
## r 0.1969518 0.4641690 0.9145154
## u 0.3946158 0.4956047 0.6192114
See: https://users.aalto.fi/~ave/CV-FAQ.html
loo(m1)
##
## Computed from 4000 by 1260 log-likelihood matrix.
##
## Estimate SE
## elpd_loo -1468.5 22.8
## p_loo 8.8 0.3
## looic 2937.1 45.7
## ------
## MCSE of elpd_loo is 0.1.
## MCSE and ESS estimates assume MCMC draws (r_eff in [0.5, 1.6]).
##
## All Pareto k estimates are good (k < 0.7).
## See help('pareto-k-diagnostic') for details.
loo(m2)
##
## Computed from 4000 by 1260 log-likelihood matrix.
##
## Estimate SE
## elpd_loo -1473.0 22.2
## p_loo 6.4 0.2
## looic 2946.0 44.4
## ------
## MCSE of elpd_loo is 0.0.
## MCSE and ESS estimates assume MCMC draws (r_eff in [0.6, 1.4]).
##
## All Pareto k estimates are good (k < 0.7).
## See help('pareto-k-diagnostic') for details.
loo::loo_compare(loo(m1), loo(m2))
## elpd_diff se_diff
## model1 0.0 0.0
## model2 -4.5 3.8