【问题标题】:Transform matrix to array assigning specific columns将矩阵转换为分配特定列的数组
【发布时间】:2020-10-21 14:24:44
【问题描述】:

我有一个大小为 17(行)x 6(列)的数字矩阵。它看起来像这样:

现在我想将此矩阵转换为大小为 2(行)x 3(列)x(17 维)的数组,其中每一行都转换为新数组中的一维,列1-3 到第一行,4-6 列到第二行。

我已经使用示例中的数字来举例说明维度 1 在这个新数组中的外观(它包括第一行的值):

如何将此矩阵转换为我想要的数组?

【问题讨论】:

    标签: r arrays matrix transform


    【解决方案1】:
    m <- matrix(c(1:12), ncol = 6)
    #     [,1] [,2] [,3] [,4] [,5] [,6]
    #[1,]    1    3    5    7    9   11
    #[2,]    2    4    6    8   10   12
    
    a <- array(t(m), dim = c(3, 2, length(m)/6))
    a <- aperm(a, c(2, 1, 3)) #switch first and second dimension
    #, , 1
    #
    #     [,1] [,2] [,3]
    #[1,]    1    3    5
    #[2,]    7    9   11
    #
    #, , 2
    #
    #     [,1] [,2] [,3]
    #[1,]    2    4    6
    #[2,]    8   10   12
    

    【讨论】:

      猜你喜欢
      • 2012-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多