/* Regression 6 - Categorical by Continuous Interactions */ clear all set seed 210316 set obs 60 scalar b0 = 1 // reference mean | x1==0, x2==0 scalar b1 = 0.75 // x1==1 difference in mean scalar b2 = 0.75 // x2==1 difference in mean scalar b12 = -0.75 // x1 AND x2 both 1, difference in mean scalar sigma = 0.75 // residual standard deviation generate x1 = runiform(0,5) generate x2 = runiformint(0,1) generate mu_y = b0 + b1*x1 + b2*x2 + b12*x1*x2 generate eps = rnormal(0, sigma) generate y = mu_y + eps * Several equivalent ways of writing the model specification regress y c.x1##x2 * regress y x1 i.x2 c.x1#i.x2 twoway (scatter y x1) (lfit y x1), by(x2) name(subsets) * To plot in one frame predict yhat separate y, by(x2) separate yhat, by(x2) sort x1 twoway (scatter y0 y1 x1) (line yhat0 yhat1 x1), name(overlay) * plot just predicted values with margins/marginsplot margins x2, at(x1=(0(0.2)5)) marginsplot marginsplot, title("E(y) ~ x1 | x2") noci ylabel(0(1)5) name(margins) addplot(scatter y x1) regress y i.x2 i.x2#c.x1 // sometimes useful, especially where some combinations of x1 and x2 don't appear bysort x2: regress y x1