waxattax
waxattax

Reputation: 357

Convert stacked matrices to block matrix

My current data is a series of 3x3 matrices that are stacked on top of one another. The structure looks like this (the following example is 3 matrices, although my actual data is much larger/longer):

0   1   1
0   0   1
1   1   0
0   1   1
1   0   1
1   0   0
0   1   1
0   0   1
1   1   0

Using R, I would like it to look like this:

0   1   1                       
0   0   1                       
1   1   0                       
            0   1   1           
            1   0   1           
            1   0   0           
                        0   1   1
                        0   0   1
                        1   1   0

Upvotes: 3

Views: 333

Answers (2)

chinsoon12
chinsoon12

Reputation: 25225

You can use split together with a variable that groups each set of 3 rows.

split(as.data.frame(mat), ceiling(seq_len(nrow(mat) / 3)))

data:

mat <- matrix(sample(0:1, 9*3, replace=TRUE), ncol=3)

Upvotes: 1

akrun
akrun

Reputation: 887148

We split the matrix to a list of matrices by a grouping index created with gl and apply bdiag (from Matrix) to get block diagonal sparse matrix

library(Matrix)
m2 <- bdiag(lapply(split(d1, as.integer(gl(nrow(d1), 3, nrow(d1)))), as.matrix))
m2
#9 x 9 sparse Matrix of class "dgCMatrix"
#                       
# [1,] . 1 1 . . . . . .
# [2,] . . 1 . . . . . .
# [3,] 1 1 . . . . . . .
# [4,] . . . . 1 1 . . .
# [5,] . . . 1 . 1 . . .
# [6,] . . . 1 . . . . .
# [7,] . . . . . . . 1 1
# [8,] . . . . . . . . 1
# [9,] . . . . . . 1 1 .

which can be converted to a regular matrix by wrapping with as.matrix

as.matrix(m2)

data

m1 <- structure(c(0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 
       1, 1, 1, 0, 1, 1, 0, 1, 1, 0), .Dim = c(9L, 3L))
d1 <- as.data.frame(m1)

Upvotes: 2

Related Questions