创建不平衡块矩阵

时间:2016-10-25 08:27:12

标签: r matrix

是否有一个通用函数在R中制作块矩阵,其中块的大小不同但每个块的内容相同?......就像这样......

#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

...但没有matrix函数中的所有重复设置

1 个答案:

答案 0 :(得分:1)

制作我自己的功能..

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