Let's look at the significance of cyl and gear on mpg in the R dataset mtcars.
car_data <- mtcars
head(car_data)
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
m0 <- lm(mpg ~ cyl * gear, data = car_data)
summary(m0)
Call:
lm(formula = mpg ~ cyl * gear, data = car_data)
Residuals:
Min 1Q Median 3Q Max
-4.8465 -2.0126 0.1848 1.4645 7.6535
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 17.1635 14.5745 1.178 0.249
cyl -0.1794 2.0458 -0.088 0.931
gear 5.1380 3.6327 1.414 0.168
cyl:gear -0.6720 0.5274 -1.274 0.213
Residual standard error: 3.198 on 28 degrees of freedom
Multiple R-squared: 0.7457, Adjusted R-squared: 0.7185
F-statistic: 27.38 on 3 and 28 DF, p-value: 1.786e-08
We can reproduce the interaction coefficient by making a dummy column
car_data$Ix <- car_data$cyl * car_data$gear
head(car_data)
mpg cyl disp hp drat wt qsec vs am gear carb Ix
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 24
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 24
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 16
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 18
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 24
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 18
We can use the dummy column to calculate the interaction coefficient
m1 <- lm(mpg ~ cyl + gear + Ix, data = car_data)
summary(m1)
Call:
lm(formula = mpg ~ cyl + gear + Ix, data = car_data)
Residuals:
Min 1Q Median 3Q Max
-4.8465 -2.0126 0.1848 1.4645 7.6535
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 17.1635 14.5745 1.178 0.249
cyl -0.1794 2.0458 -0.088 0.931
gear 5.1380 3.6327 1.414 0.168
Ix -0.6720 0.5274 -1.274 0.213
Residual standard error: 3.198 on 28 degrees of freedom
Multiple R-squared: 0.7457, Adjusted R-squared: 0.7185
F-statistic: 27.38 on 3 and 28 DF, p-value: 1.786e-08
Although the interaction is not significant, for the sake of argument let's pretend it is. Let's imagine also, we want to know the significance of the cyl effect on mpg at a gear of 4. We can deduce that effect using glht and no dummy columns.
library(multcomp)
summary(glht(lm(mpg ~ cyl * gear, data = car_data),linfct=c("cyl + 4 * cyl:gear == 0"), test = adjusted("none")))
Simultaneous Tests for General Linear Hypotheses
Fit: lm(formula = mpg ~ cyl * gear, data = car_data)
Linear Hypotheses:
Estimate Std. Error t value Pr(>|t|)
cyl + 4 * cyl:gear == 0 -2.8673 0.3822 -7.502 3.59e-08 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
(Adjusted p values reported -- single-step method)
Is there any way to reproduce this calculation of a main effect at the level of an interaction using a dummy variable?
Many thanks