R: How to construct a repeated identity matrix

Viewed 158

Is there a function in R to easily construct a repeated identity matrix (not sure if this is the correct term)?

This is what I am currently using but it is a bit cumbersome and un-intuitive:

Ngroups   <- 3
NperGroup <- 2
Z <- diag(Ngroups)[rep(1:Ngroups, each = NperGroup), ]

> Z
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    1    0    0
[3,]    0    1    0
[4,]    0    1    0
[5,]    0    0    1
[6,]    0    0    1
1 Answers

Here is one way...

diag(3) %x% c(1,1)

     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    1    0    0
[3,]    0    1    0
[4,]    0    1    0
[5,]    0    0    1
[6,]    0    0    1

In your case diag(Ngroups) %x% rep(1,NperGroup) would do it. See ?kronecker for further options

Related