data(mtcars)
mtcars$cyl <- factor(mtcars$cyl)
mtcars$am <- factor(mtcars$am)
Intercept <- rep(1, nrow(mtcars)) #Intercept column would be 1
cyl6 <- ifelse(mtcars$cyl == "6", 1, 0) #Main effects of cyl
cyl8 <- ifelse(mtcars$cyl == "8", 1, 0)
am1 <- ifelse(mtcars$am == "1", 1, 0) #Main effects of transmission
cyl6_am1 <- cyl6 * am1 #interaction effect
cyl8_am1 <- cyl8 * am1
X_manual <- cbind( Intercept, cyl6, cyl8, am1, cyl6_am1, cyl8_am1)
colnames(X_manual) <- c( "(Intercept)","cyl6","cyl8", "am1", "cyl6:am1",
"cyl8:am1"
)
dim(X_manual)
## [1] 32 6
X_manual[1:10, ] #subset of the design matrix
## (Intercept) cyl6 cyl8 am1 cyl6:am1 cyl8:am1
## [1,] 1 1 0 1 1 0
## [2,] 1 1 0 1 1 0
## [3,] 1 0 0 1 0 0
## [4,] 1 1 0 0 0 0
## [5,] 1 0 1 0 0 0
## [6,] 1 1 0 0 0 0
## [7,] 1 0 1 0 0 0
## [8,] 1 0 0 0 0 0
## [9,] 1 0 0 0 0 0
## [10,] 1 1 0 0 0 0
X_auto <- model.matrix(mpg ~ cyl * am, data = mtcars)
#comparing it with model.matrix to check if my manual X is correct
all(X_manual == X_auto)
## [1] TRUE