[R] Order of terms and model.matrix()
Axel Urbiz
axel.urbiz at gmail.com
Thu Jan 7 16:14:04 CET 2016
Hello,
It is not very clear to me from the model.matrix documentation, why simply
changing the order of terms in the formula may give a different design
matrix. Please note I’m purposely not including main effects in the model
formulae.
set.seed(1)
x1 <- rnorm(100)
f1 <- factor(sample(letters[1:3], 100, replace = TRUE))
trt <- sample(c(-1,1), 100, replace = TRUE)
df <- data.frame(y=y, x1=x1, f1=f1, trt=trt)
head(model.matrix( ~ x1:trt + f1:trt, data = df))
(Intercept) x1:trt trt:f1b trt:f1c
1 1 -0.62036668 1 0
2 1 0.04211587 0 0
3 1 -0.91092165 0 1
4 1 0.15802877 0 1
5 1 0.65458464 0 -1
6 1 1.76728727 0 1
head(model.matrix(~ f1:trt + x1:trt, data = df)) #terms reversed
(Intercept) f1a:trt f1b:trt f1c:trt trt:x1
1 1 0 1 0 -0.62036668
2 1 1 0 0 0.04211587
3 1 0 0 1 -0.91092165
4 1 0 0 1 0.15802877
5 1 0 0 -1 0.65458464
6 1 0 0 1 1.76728727
Thanks,
Axel.
[[alternative HTML version deleted]]
More information about the R-help
mailing list