Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an unbalanced block matrix

Tags:

r

matrix

Is there a general function to make block matrices in R, where the blocks are different sizes but the content of each block is the same?... something like this...

#block size 
bb <- c(2,3,4,2) 
dn <- rep(LETTERS[1:4], times = bb)
#block contents based on 1:16 sequence
matrix(c( 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4,
          1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 
          5, 5, 6, 6, 6, 7, 7, 7, 7, 8, 8, 
          5, 5, 6, 6, 6, 7, 7, 7, 7, 8, 8,
          5, 5, 6, 6, 6, 7, 7, 7, 7, 8, 8,
          9, 9,10,10,10,11,11,11,11,12,12,
          9, 9,10,10,10,11,11,11,11,12,12,
          9, 9,10,10,10,11,11,11,11,12,12,
          9, 9,10,10,10,11,11,11,11,12,12,
         13,13,14,14,14,15,15,15,15,16,16,
         13,13,14,14,14,15,15,15,15,16,16), 
       byrow = TRUE, nrow = sum(bb), ncol = sum(bb), dimnames = list(dn, dn))

#    A  A  B  B  B  C  C  C  C  D  D
# A  1  1  2  2  2  3  3  3  3  4  4
# A  1  1  2  2  2  3  3  3  3  4  4
# B  5  5  6  6  6  7  7  7  7  8  8
# B  5  5  6  6  6  7  7  7  7  8  8
# B  5  5  6  6  6  7  7  7  7  8  8
# C  9  9 10 10 10 11 11 11 11 12 12
# C  9  9 10 10 10 11 11 11 11 12 12
# C  9  9 10 10 10 11 11 11 11 12 12
# C  9  9 10 10 10 11 11 11 11 12 12
# D 13 13 14 14 14 15 15 15 15 16 16
# D 13 13 14 14 14 15 15 15 15 16 16

... but without all the repetitive set up in the matrix function

like image 411
guyabel Avatar asked May 10 '26 03:05

guyabel


1 Answers

Made my own function..

my_matrix <- function(x, b){
  n <- length(b)
  bb <- rep(1:4, times = b)
  xx <- matrix(NA, nrow = sum(b), ncol = sum(b))
  k <- 1
  for(i in 1:n){
    for(j in 1:n){
      xx[i==bb, j==bb] <- x[k]
      k <- k+1
    }
  }
  xx
}

my_matrix(x = 1:16, b = c(2,3,4,2))
#       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
#  [1,]    1    1    2    2    2    3    3    3    3     4     4
#  [2,]    1    1    2    2    2    3    3    3    3     4     4
#  [3,]    5    5    6    6    6    7    7    7    7     8     8
#  [4,]    5    5    6    6    6    7    7    7    7     8     8
#  [5,]    5    5    6    6    6    7    7    7    7     8     8
#  [6,]    9    9   10   10   10   11   11   11   11    12    12
#  [7,]    9    9   10   10   10   11   11   11   11    12    12
#  [8,]    9    9   10   10   10   11   11   11   11    12    12
#  [9,]    9    9   10   10   10   11   11   11   11    12    12
# [10,]   13   13   14   14   14   15   15   15   15    16    16
# [11,]   13   13   14   14   14   15   15   15   15    16    16       
like image 168
guyabel Avatar answered May 12 '26 17:05

guyabel