如何以特定方式制作model.matrix?

时间:2014-02-27 22:24:42

标签: r model.matrix

如何使用model.matrix生成看起来像这样的矩阵?

      [,1] [,2] [,3] [,4] [,5] [,6]
 [1,]    1    1    0    0    0    0
 [2,]    1    2    0    0    0    0
 [3,]    1    3    0    0    0    0
 [4,]    0    0    1    1    0    0
 [5,]    0    0    1    2    0    0
 [6,]    0    0    1    3    0    0
 [7,]    0    0    0    0    1    1
 [8,]    0    0    0    0    1    2
 [9,]    0    0    0    0    1    3

我通过

制作了第一个矩阵
fit = lmer(Temp ~ 1 + (1 + Time|Id), data = Data) 
getME(fit, name = c("Z"))

哪里

Time = rep(1:3, 3)

和Id

Id = c(0L, cumsum(diff(Time) < 0))

这是我能得到的尽可能接近。

id = rep(c("a","b","c"),each = 3)
Z = model.matrix(~0+id)

  [,1] [,2] [,3]
1    1    0    0
2    1    0    0
3    1    0    0
4    0    1    0
5    0    1    0
6    0    1    0
7    0    0    1
8    0    0    1
9    0    0    1

1 个答案:

答案 0 :(得分:2)

我不确定我会尝试做什么,但这对你有用吗?

val = rep(1:3,3)
z = model.matrix(~0+id+id:val)