1
在R,我们可以使用model.matrix()
构建设计矩阵,例如,转换model.matrix中的R的一组向量
grp.ids = as.factor(c(rep(1,8), rep(2,4), rep(3,2)))
x = model.matrix(~grp.ids)
给出了设计矩阵x
:
(Intercept) grp.ids2 grp.ids3
1 1 0 0
2 1 0 0
3 1 0 0
4 1 0 0
5 1 0 0
6 1 0 0
7 1 0 0
8 1 0 0
9 1 1 0
10 1 1 0
11 1 1 0
12 1 1 0
13 1 0 1
14 1 0 1
attr(,"assign")
[1] 0 1 1
attr(,"contrasts")
attr(,"contrasts")$grp.ids
[1] "contr.treatment"
然而,如果现在我得到如上的设计矩阵x
,并希望通过某种方式获得“分组向量”grp.ids
x
。我怎样才能做到这一点?谢谢!
谢谢你的解决方案!我认为每个组别使用什么数字并不重要,因为他们只是因素水平:) – alittleboy
顺便说一句,有没有什么办法让水平按升序排列?我目前有1,3,2,但希望获得1,2,3。这样,当我重建model.matrix时,我可以得到相同的结果。谢谢。 – alittleboy
@alittleboy为你添加了一个更新 – Dason