Interactions in stan


I have recently made the switch from brms to rstan. Could someone point me to a reference on how to do interactions in stan? I have googled it but the only examples I found were relatively complex (for a beginner).


Easiest way to do it is with a contrast matrix. See this lecture


I often point to @mike-lawrence’s videos for my students and colleagues who needs a more in-depth view of certain concepts. They are a gold mine.

1 Like

Hoping to someday have time to go back and redo things with proper prior predictive checks and posterior predictive checks.

1 Like

Yes, that’s missing a bit now, but could easily be added :)

Hello. Thank you @mike-lawrence for pointing me to the video. I have created a contrast matrix with my interaction terms (called Inter). Below is my code. My regression is multivariate so I don’t think I can do it exactly how it’s executed in the video. I am trying to estimate the impact the promotion has on TV Spend’s contribution to sales. I am getting syntax errors in the transformed parameter section. My bigger question, though, is this the correct way to to a multivariate regression with an interaction where the interaction is combination of a real variable and an integer variable? Thanks in advance!

data {
 int < lower = 1 > N; // number of observations
 vector[N] y; // outcome 
 vector[N] TV_Spend ;   // TV Spend regressor
 int Promo[N]; // Promo indicator
 matrix[N,N] Inter; //Interaction

parameters {
 real<lower=0> alpha; // Intercept
 vector[N] beta1; //Promo coefficient
 vector[N] beta2; //TV_Spend coefficient
 vector[N] beta3; //Interaction coefficient
 real < lower = 0 > sigma; // Error Term

transformed parameters {
  real mu[N] ;                    
  for (i in 1:N) {
    mu[i] = alpha + beta1[Promo[i]] + beta2*TV_Spend[i] + beta3*Inter[i]; //Is this right??

model {
  // The likelihood
  y ~ normal(mu, sigma); 


Note: i haven’t included all the other variables yet like Direct Mail spend, etc that I will add later.

Depends on what you mean by “integer variable”. If you mean a variable that has just two ordered levels, nothing is different there; just turn it to a factor and set its contrasts to what you prefer or hand code the variable to a numeric yourself. If instead you mean a variable that is 3+ ordinal levels, then I’d be outside my realm of direct experience but think you might look to a latent ordinal model for that variable then use the latent propensity parameter as the predictor/interaction-multiplier rather than the manifest ordinal observations.