是否有一个通用功能可以在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
函数中进行所有重复设置 最佳答案
发挥了自己的作用。
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