We create 3 matrix
of 1 in list
, construct a block diagonal matrix with bdiag
double negation to force binary to logical, replace TRUE elements of NA, multiply by 'm1' to get 'm2'.
library(Matrix)
m2 <- as.matrix((NA^!!bdiag(lapply(1:3, matrix, data=1,ncol=2, nrow=2)))*m1)
m2
We remove the elements NA
in each row using apply
c MARGIN=1
to get the expected result.
t(apply(m2, 1, function(x) x[!is.na(x)]))
# [,1] [,2] [,3] [,4]
#[1,] 12 98 32 99
#[2,] 13 2 31 78
#[3,] 25 85 46 87
#[4,] 98 98 45 48
#[5,] 88 0 68 99
#[6,] 5 33 66 12
data
m1 <- structure(c(23L, 54L, 25L, 98L, 88L, 5L, 98L, 11L, 85L, 98L,
0L, 33L, 12L, 13L, 15L, 16L, 68L, 66L, 98L, 2L, 9L, 17L, 99L,
12L, 32L, 31L, 46L, 45L, 89L, 14L, 99L, 78L, 87L, 48L, 89L, 78L
), .Dim = c(6L, 6L))