[R] Order of formula terms in model.matrix

Lars Bishop lars52r at gmail.com
Sun Jan 17 14:42:51 CET 2016


I’d appreciate your help on understanding the following. 

It is not very clear to me from the model.matrix documentation, why simply changing the order of terms in the formula may change the number of resulting columns. Please note I’m purposely not including main effects in the model formula in this case. 
 

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(x1=x1, f1=f1, trt=trt)

dim(model.matrix( ~ x1:trt + f1:trt, data = df))
[1] 100 4

dim(model.matrix(~ f1:trt + x1:trt, data = df))
[1] 100 5


Thanks,
Lars. 


More information about the R-help mailing list