# [R] Data Manipulation - make diagonal matrix of each element of a matrix

Clemontina Alexander ckalexa2 at ncsu.edu
Thu Dec 15 16:02:28 CET 2011

```Dear R list,
I have the following data:

set.seed(1)
n  <- 5     # number of subjects
tt <- 3     # number of repeated observation per subject
numco <- 2  # number of covariates
x <- matrix(round(rnorm(n*numco),2), ncol=numco)   # the actual covariates
x
> x
[,1]  [,2]
[1,] -0.63 -0.82
[2,]  0.18  0.49
[3,] -0.84  0.74
[4,]  1.60  0.58
[5,]  0.33 -0.31

I need to form a matrix X such that
X =      x11      0      0     x21      0      0
0   x11      0        0   x21      0
0      0   x11        0      0   x21
x12      0      0     x22      0      0
0   x12      0        0   x22      0
0      0   x12        0      0   x22
...
x15      0      0     x25      0      0
0   x15      0        0   x25      0
0      0   x15        0      0   x25
where both tt and numco can change. (So if tt=5 and numco=4, then X
needs to have 20 columns and n*tt rows. Each diagonal matrix should be
5x5 and there will be 4 of them for the 4 covariates.) I wrote this
funky for loop:

idd <- length(diag(1,tt))    # length of intercept matrix
X <- matrix(numeric(n*numco*idd),ncol=tt*numco)
for(i in 1:numco){
X[,((i-1)*tt+1):(i*tt)] <- matrix(
c(matrix(rep(diag(1,tt),n),ncol=tt, byrow=TRUE))   *
rep(rep(x[,i],each=tt),tt)
, ncol=tt)
}
X

It works fine, but is there an easier way when n, tt, and numco get
larger and larger?
Thanks,
Tina

--
Clemontina Alexander
Ph.D Student
Department of Statistics
NC State University
Email: ckalexa2 at ncsu.com

```