[R] about model.matrix

Fix Ace acefix at rocketmail.com
Wed Apr 1 07:28:27 CEST 2015


I tried to run the sample code from R:
dd <- data.frame(a = gl(3,4), b = gl(4,1,12))   a b
1  1 1
2  1 2
3  1 3
4  1 4
5  2 1
6  2 2
7  2 3
8  2 4
9  3 1
10 3 2
11 3 3
12 3 4
options("contrasts")
model.matrix(~ a + b, dd)(Intercept) a2 a3 b2 b3 b4
1            1  0  0  0  0  0
2            1  0  0  1  0  0
3            1  0  0  0  1  0
4            1  0  0  0  0  1
5            1  1  0  0  0  0
6            1  1  0  1  0  0
7            1  1  0  0  1  0
8            1  1  0  0  0  1
9            1  0  1  0  0  0
10           1  0  1  1  0  0
11           1  0  1  0  1  0
12           1  0  1  0  0  1
when I tried to remove the intercept from the matrix, I used the following codemodel.matrix(~ 0+a + b, dd)
 a1 a2 a3 b2 b3 b41 1 0 0 0 0 02 1 0 0 1 0 03 1 0 0 0 1 04 1 0 0 0 0 15 0 1 0 0 0 06 0 1 0 1 0 07 0 1 0 0 1 08 0 1 0  0 0 19 0 0 1 0 0 010 0 0 1 1 0 011 0 0 1 0 1 012 0 0 1 0 0 1 when I tried to remove the intercept

Here I noticed that, all levels of a, a1, a2, and a3, were included. I wonder how  I can include the "b1" in the matrix as well?   a1 a2 a3 b1 b2 b3 b4
1   1  0  0  1  0  0  0
2   1  0  0  0  1  0  0
3   1  0  0  0  0  1  0
4   1  0  0  0  0  0  1
5   0  1  0  1  0  0  0
6   0  1  0  0  1  0  0
7   0  1  0  0  0  1  0
8   0  1  0  0  0  0  1
9   0  0  1  1  0  0  0
10  0  0  1  0  1  0  0
11  0  0  1  0  0  1  0
12  0  0  1  0  0  0  1 

	[[alternative HTML version deleted]]



More information about the R-help mailing list