Stata Interaction Syntax: When to Use # vs ## in Clinical Models
- Mayta
- Jul 2
- 2 min read
🔍 Why This Matters
Clinical models are often multifactorial:
Repeated measurements (e.g., over time)
Group allocations (e.g., control/intervention)
Strata or contexts (e.g., site, sex, ward)
To test how one factor modifies another, you need interaction terms, and Stata gives you two powerful syntaxes: ## and #.
🔢 Core Syntax Rules
Syntax | Meaning | Includes Main Effects? | Includes Interaction? |
A#B | Just the interaction term A×B | ❌ No | ✅ Yes |
A##B | Main effects of A, B, and A×B interaction | ✅ Yes | ✅ Yes |
✅ Use ## When:
You want a complete model: main effects + interaction
You want to estimate treatment effects across strata/time
You plan to use margins, marginsplot, or need full interpretability
Always prefer ## unless you're 100% sure you've already added main effects elsewhere.
🧭 When You Use More Than 2 Factors
Stata lets you combine:
i.section##i.group_bin##c.month
This expands to:
Main: section, group_bin, month
2-way interactions: section#group_bin, group_bin#month, section#month
3-way interaction: section#group_bin#month
Perfect for: Modeling treatment effects over time, stratified by site, sex, or any other context.
🔁 Variable Order in ##: Does It Matter?
NO. Mathematically, it’s identical.
i.A##i.B
= same model as:
i.B##i.A
Only the labels change in output (e.g., 2.sex#1.treat vs 1.treat#2.sex).
📌 Rule of thumb:
Put your focus variable first to keep labels intuitive.
💡 Clinical Examples
1. Time-varying Treatment Effect
mixed outcome i.group##c.month || id:
Tests: Does treatment effect change over time?
2. Site-Treatment Interaction
mixed outcome i.section##i.group_bin || id:
Tests: Is treatment effect different across sections (e.g., clinics)?
3. Fully Stratified Longitudinal Model
mixed outcome i.section##i.group_bin##c.month || id:
Tests: Does treatment effect over time vary across sections?
📊 Margins and Visualization
margins section#group_bin#month
marginsplot
→ Gives you a visual of the interaction effect across combinations, ideal for papers and presentations.
🧾 Final Takeaways
Situation | Use Syntax |
You want main + interaction | A##B |
You want just interaction (rare) | A#B |
You have >2 interacting factors | Chain with ## |
You care about label readability | Put focus variable first |
🔓 Want sample code + margins tables for your specific model? Just drop your variables, and I’ll plug them in.
Comments