在R中的大矩阵中更改值块

时间:2016-09-27 23:40:34

标签: r matrix

我有1000x1000条目的大矩阵。 1是按块组织的,它们总是与其他块分开,而不是在下一个块的行或列上重叠。为您举例说明12x12矩阵,该矩阵由3个1s块组成:

      111100000000
      111100000000
      111100000000
      111100000000
      000011110000
      000011110000
      000011110000
      000011110000
      000000001111
      000000001111
      000000001111
      000000001111

我希望R将矩阵转换成这样的东西(无论矩阵的大小):

      111100000000
      111100000000
      111100000000
      111100000000
      000022220000
      000022220000
      000022220000
      000022220000
      000000003333
      000000003333
      000000003333
      000000003333

提前致谢!

数据

structure(c(1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 
0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 
1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 
0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 
0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 
1), .Dim = c(12L, 12L))

1 个答案:

答案 0 :(得分:2)

将矩阵乘以块组。 0' s将保持不变,并且将取其组值:

len <- sum(mat[,1])
mat * rep(1:(nrow(mat)/len), each=len)
#       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
# [1,]     1    1    1    1    0    0    0    0    0     0     0     0
# [2,]     1    1    1    1    0    0    0    0    0     0     0     0
# [3,]     1    1    1    1    0    0    0    0    0     0     0     0
# [4,]     1    1    1    1    0    0    0    0    0     0     0     0
# [5,]     0    0    0    0    2    2    2    2    0     0     0     0
# [6,]     0    0    0    0    2    2    2    2    0     0     0     0
# [7,]     0    0    0    0    2    2    2    2    0     0     0     0
# [8,]     0    0    0    0    2    2    2    2    0     0     0     0
# [9,]     0    0    0    0    0    0    0    0    3     3     3     3
# [10,]    0    0    0    0    0    0    0    0    3     3     3     3
# [11,]    0    0    0    0    0    0    0    0    3     3     3     3
# [12,]    0    0    0    0    0    0    0    0    3     3     3     3

修改

如果块组在矩阵内变化,我们将不得不区分一个块结束而另一个块开始使用它:

library(data.table)
mat * rleid(apply(mat, 1, paste, collapse=""))