library(bmm)Using bmm on your own data
The bridge from the workshop demos to your dataset
The workshop shows three models on three tidy datasets that were prepared in advance. Your data is not tidy, your paradigm is probably not one of those three, and nobody is standing next to you when the first error appears. This notebook is about that gap.
Work through it in order. Each step answers one question, and each has a way to check that you got it right before moving on.
Step 1: Is my paradigm covered?
Before anything else, find out whether bmm already has a model for the task you ran. Ask the package rather than searching the documentation:
supported_models()The following models are supported:
Continuous reproduction
- imm(): Interference measurement model by Oberauer and Lin (2017)
- mixture2p(): Two-parameter mixture model by Zhang and Luck (2008)
- mixture3p(): Three-parameter mixture model by Bays et al (2009)
- sdm(): Signal Discrimination Model (SDM) by Oberauer (2023)
Categorical recall and n-AFC decisions
- m3(): The Multinomial / Memory Measurement Model
Processing-tree models
- mpt(): Multinomial Processing Tree (MPT) models
Detection, recognition and confidence judgments
- sdt_cdp(): Continuous Dual-Process Signal Detection Theory (CDP)
- sdt_mafc(): Signal Detection Theory (m-AFC)
- sdt_ranking(): Signal Detection Theory (Ranking)
- sdt_rating(): Signal Detection Theory (Confidence Rating)
- sdt_yn(): Signal Detection Theory (Yes/No)
Choices and response times
- cswald(): Censored-Shifted Wald Model
- ddm(): Diffusion Decision Model
- ezdm(): EZ-Diffusion Model
Type ?modelname to get information about a specific model, e.g. ?imm
Grouped by the kind of task that produces them:
| If your task is… | The measurement models are | Demoed today? |
|---|---|---|
| Old/new recognition or detection, yes/no responses | sdt_yn() |
✅ Part 1 |
| The same, with confidence ratings | sdt_rating(), sdt_cdp() |
✅ Part 1 |
| m-alternative forced choice, or ranking a set | sdt_mafc(), sdt_ranking() |
— |
| Span / recall scored into response categories | m3() |
✅ Part 2 |
| Speeded two-choice decisions with RTs | ddm(), lba(), lnr(), rdm(), cswald() |
✅ Part 3 |
| The same, but you only have summary statistics | ezdm() |
✅ Part 3 |
| Continuous reproduction (colour/orientation wheel) | mixture2p(), mixture3p(), imm(), sdm() |
— |
| Change detection with a continuous feature space | mixture2p_cd(), mixture3p_cd(), imm_cd(), sdm_cd() |
— |
| Anything you can draw as a processing tree | mpt() |
— |
| Choice under risk with payoffs | utility() |
— |
Two honest caveats.
Your paradigm may not be here. bmm covers a broad but finite set of measurement models. If your task is not on this list, the question becomes whether it can be expressed as one of them — a lot of paradigms reduce to an MPT, and mpt() is deliberately general. If it genuinely cannot, bmm is not your tool, and that is a useful thing to learn in five minutes rather than five weeks.
“Covered” is not “appropriate”. A model that accepts your data can still be the wrong model for your question. ?modelname gives the assumptions each one makes; the papers in resources/ are where the reasoning lives.
?sdt_yn # or ?m3, ?ddm, ?imm — one help page per modelStep 2: What shape does my data need?
This is where most first attempts fail, and it is entirely mechanical. Every bmm model tells you what it wants — just print it.
sdt_yn(response = "n_old", stimulus = "is_old", n_trials = "n_trials")sdt_yn(response = "n_old", stimulus = "is_old", n_trials = "n_trials")
Response: response = n_old (count of 'old'/'signal' responses per cell)
Parameters: d, criterion, bias, sdratio
Links: d = identity; criterion = identity; bias = identity; sdratio = log
Fixed: sdratio = 0
Use parameter_info() for parameter descriptions, links and fixed values.
The Response: block is the contract. Here it says: one column of counts of “old” responses, and — because counts are involved — one row per participant × stimulus class rather than one row per trial.
Compare a trial-level model, where no aggregation is needed at all:
ddm(rt = "rt", response = "resp")ddm(rt = "rt", response = "resp")
Response: rt = rt (seconds)
response = resp (0/1 or logical; 1 = upper boundary)
Parameters: drift, bound, ndt, zr
Links: drift = identity; bound = log; ndt = log; zr = logit
Fixed: zr = 0, mu = 0
Use parameter_info() for parameter descriptions, links and fixed values.
Two different worlds, and knowing which one you are in determines everything about your data preparation:
| Model family | One row per… | You must aggregate first |
|---|---|---|
sdt_yn(), sdt_rating(), sdt_mafc(), m3(), mpt(), ezdm() |
participant × cell of the design | yes — counts |
ddm(), lba(), lnr(), rdm(), imm(), sdm(), mixture*() |
trial | no |
Aggregating trial-level data to counts
If your model wants counts, the move is always the same shape — group by participant and every design variable you plan to put in a formula, then count:
library(tidyverse)
counts <- my_trials |>
summarise(
n_old = sum(said_old), # the response being counted
n_trials = n(), # how many trials that count came from
.by = c(pid, condition, is_old)
)
head(counts)Two rules that catch most mistakes:
- Every variable you want in a formula must survive into the aggregated data. If
conditionis not in.by =, you cannot later writed ~ condition— the column will not exist. This is the most common cause of “why does my model ignore my manipulation”. - Do not aggregate across the stimulus class. SDT needs the old items and the new items kept apart; that is what
is_oldis doing in.by =. Aggregating over it destroys exactly the information the model exists to use.
For rating-scale models you need one count column per response category, and categories with zero observations must be present as zeros rather than missing:
rating_counts <- my_trials |>
count(pid, condition, is_old, rating) |>
complete(nesting(pid, condition, is_old), rating, fill = list(n = 0)) |> # <- the zeros
pivot_wider(names_from = rating, values_from = n, names_prefix = "r",
values_fill = 0)Dropping that complete() line is a silent error: the model fits, and the estimates are wrong, because a participant who never used “sure new” looks like a participant who was never offered it.
For M3, see the worked example for counting responses by participant, set size, and option combination, and recording how many options were available in each category.
Step 3: Writing the formula for your design
The workshop example has one between-subjects factor. Yours probably does not. The good news is that this is ordinary R formula syntax on the left-hand side of a parameter name — everything you know from lm() and lmer() transfers directly.
# Between-subjects factor (the workshop example)
bmf(d ~ 1 + group + (1 | pid))
# Within-subjects factor — the random slope is what makes it "within"
bmf(d ~ 1 + condition + (1 + condition | pid))
# Two factors and their interaction
bmf(d ~ 1 + condition * session + (1 + condition * session | pid))
# A continuous covariate (centre it first — the intercept is then interpretable)
bmf(d ~ 1 + age_c + (1 | pid))
# Crossed participants and items
bmf(d ~ 1 + condition + (1 + condition | pid) + (1 | item))
# One parameter varies, another is held constant across conditions —
# this is a *theoretical* claim, and often the most interesting model
bmf(d ~ 1 + condition + (1 + condition | pid),
criterion ~ 1 + (1 | pid))Three things worth internalising:
- You write one formula per parameter, and you choose which. Any parameter you do not name gets an intercept only. Deciding that memory varies with your manipulation but bias does not — or vice versa — is your hypothesis, expressed in code.
- The left-hand side must be a parameter name, not a column in your data. The error names the legal ones, and
parameter_info(model)describes them.bmm_data_check(formula, data, model)runs that check, and bmm’s data checks, before anything compiles: make it the first call on your own data. (1 | pid)is not optional in practice. Without it, every participant is assumed to have the same parameter value, and the uncertainty you report will be far too small.
A worked translation
Say you ran a recognition task with 60 participants, each doing two blocks (massed vs spaced study), and you also recorded their age. You want to know whether spacing improves memory, whether it changes response bias, and whether older participants are more conservative.
counts <- trials |>
summarise(n_old = sum(said_old), n_trials = n(),
.by = c(pid, spacing, is_old, age_c))
fit <- bmm(
formula = bmf(
d ~ 1 + spacing + (1 + spacing | pid),
criterion ~ 1 + spacing + age_c + (1 + spacing | pid)
),
data = counts,
model = sdt_yn(response = "n_old", stimulus = "is_old",
n_trials = "n_trials"),
sample_prior = "yes" # prior draws: Bayes factors in hypothesis()
)Each of the three questions is now one coefficient: d_spacingspaced, criterion_spacingspaced, criterion_age_c. Testing them is hypothesis(fit, "d_spacingspaced > 0").
Step 4: Can I actually fit it?
Here is the part the workshop deliberately skips. Every model you saw was pre-fitted — loaded with readRDS(), never sampled. That is what let us promise “no Stan toolchain required”, and it means the very first thing you have to do with your own data is the one thing that was never demonstrated.
Fitting requires a C++ toolchain and a Stan backend. Budget an hour the first time, and do it on a day when you are not also trying to answer a research question.
# 1. A compiler.
# macOS: run xcode-select --install in Terminal
# Windows: install Rtools, matched to your R version, from
# https://cran.r-project.org/bin/windows/Rtools/
# Linux: you almost certainly already have one (build-essential)
# 2. cmdstanr (not on CRAN — it has its own repository)
install.packages("cmdstanr",
repos = c("https://stan-dev.r-universe.dev", getOption("repos")))
# 3. Check the compiler BEFORE installing anything else. fix = TRUE
# repairs the common problems by itself.
cmdstanr::check_cmdstan_toolchain(fix = TRUE)
# 4. Install CmdStan itself. This compiles a lot of C++ — 10-20 minutes,
# and a wall of output that is not an error.
cmdstanr::install_cmdstan()
# 5. Tell brms to use it. Put this in every script that fits a model.
options(brms.backend = "cmdstanr", mc.cores = 4)What success looks like. Step 3 prints The C++ toolchain required for CmdStan is setup properly. Step 4 ends with CmdStan path set to: and a directory. Since bmm 1.4.1, one call runs all of these checks and compiles and samples a small test model, with one fix suggested for every check that fails:
bmm::bmm_setup()If you got both of those lines, or bmm_setup() reports no failed check, you are done — the following will fit in well under a minute and is the smallest possible end-to-end test:
library(brms)
options(brms.backend = "cmdstanr", mc.cores = 4)
test <- brm(mpg ~ hp, data = mtcars, chains = 2, iter = 500, refresh = 0)
summary(test)If brm() on mtcars works, your toolchain is fine and any later problem is about your model or your data — a genuinely useful thing to be able to rule out.
Step 5: What breaks first
Real error messages, in roughly the order people meet them. bmm_data_check(formula, data, model) reports the second, third and fourth of these before anything compiles, so run it first.
could not find function "sdt_yn"
Your bmm is older than 1.4.1, the release that added the SDT models (CRAN, October 2026). Update it:
install.packages("bmm")The same message for any other model name means the same thing: check supported_models() against packageVersion("bmm").
Unrecognized model parameters: 'dprime'
The left-hand side of a formula is not a parameter of this model. bmm’s sensitivity parameter is called d. Ask, do not guess:
parameter_info(sdt_yn(response = "n_old", stimulus = "is_old",
n_trials = "n_trials"))Stimulus variable 'is_old_' missing in the data
A column name in the model specification does not exist in your data frame. Typo, or a column that got dropped during aggregation. names(counts) settles it in one line.
Variables 'n_old', 'n_trials' missing in the data
You passed trial-level data to a model that wants counts. Go back to Step 2 and aggregate.
It compiles, then runs for hours
Trial-level RT models on large datasets are genuinely slow, and hierarchical models scale with the number of participants and random effects. Before assuming something is wrong, fit a deliberately small version first — two participants, chains = 2, iter = 500 — to confirm the model is well specified. Then scale up. Never debug a specification on a four-hour fit.
Divergent transitions after warmup
The sampler is telling you the geometry of your posterior is difficult, usually because the model is too flexible for the data you have. In order of what to try: raise control = list(adapt_delta = 0.95); simplify the random-effects structure (a full (1 + a * b | pid) on a within-design needs a lot of trials per cell to be identified); set more informative priors. A handful of divergences with good Rhat is usually survivable; hundreds is not.
Step 6: Did it actually work?
Never report an estimate without looking at these three things.
summary(fit) # Rhat, Bulk_ESS, Tail_ESS per parameter
pp_check(fit) # does the model reproduce your data?Rhatshould be 1.00 for every parameter. Above ~1.01 means the four chains have not converged on the same answer, and the estimates are not usable — no interpretation, no plotting, fix it first.Bulk_ESS/Tail_ESSare how many independent draws your correlated MCMC draws are worth. A few hundred suffices for a point estimate; want >1000 before quoting the edges of an interval.pp_check()simulates data from the fitted model and overlays your real data. If the two look nothing alike, the parameters are precisely estimated values of a model that does not describe your task — the most dangerous failure mode, because nothing in the numbers complains.
One more that costs nothing and catches a lot: fit the model to data you simulated from known parameter values, and check that it recovers them. If it cannot recover parameters from data the model itself generated, it will not recover them from yours. Every bmm model ships with a simulation function (rsdt_yn(), rsdt_rating(), and so on) for exactly this.
Where to get help
?modelnameandvignette(package = "bmm")— the model-specific documentation, which is more detailed than anything in this workshop.- The reading list in
resources/README.md, with DOIs — for the theory behind each model rather than the code. - github.com/popov-lab/bmm/issues — bugs and feature requests. A reproducible example with 10 rows of data gets answered; “it doesn’t work” does not.
- The three of us. If you get stuck on the translation step — which model, what data shape, what formula — send us ten rows of your data and a sentence about your design, and we will write the formula with you. That offer is the reason this notebook exists.