更改矩阵尺寸并按行

时间:2017-06-29 22:23:03

标签: r matrix

在R中我想知道如何重构以下矩阵:

自:

m = matrix( c("p.b1.1", "p.b1.2", "p.b1.3", "p.b1.4", "p.b2.1", "p.b2.2", "p.b2.3", 
              "p.b2.4", "p.b3.1", "p.b3.2", "p.b3.3", "p.b3.4", "p.b4.1", "p.b4.2", 
              "p.b4.3", "p.b4.4", "p.b5.1", "p.b5.2", "p.b5.3", "p.b5.4", "p.b6.1", 
              "p.b6.2", "p.b6.3", "p.b6.4", "p.b7.1", "p.b7.2", "p.b7.3", "p.b7.4"))

到:

       [,1]     [,2]     [,3]     [,4]    
[1,] "p.b1.1" "p.b1.2" "p.b1.3" "p.b1.4"
[2,] "p.b2.1" "p.b2.2" "p.b2.3" "p.b2.4"
[3,] "p.b3.1" "p.b3.2" "p.b3.3" "p.b3.4"
[4,] "p.b4.1" "p.b4.2" "p.b4.3" "p.b4.4"
[5,] "p.b5.1" "p.b5.2" "p.b5.3" "p.b5.4"
[6,] "p.b6.1" "p.b6.2" "p.b6.3" "p.b6.4"
[7,] "p.b7.1" "p.b7.2" "p.b7.3" "p.b7.4"`

2 个答案:

答案 0 :(得分:2)

运行以下操作应该可以解决问题:

matrix(m, ncol = 4, byrow = TRUE)
#     [,1]     [,2]     [,3]     [,4]    
#[1,] "p.b1.1" "p.b1.2" "p.b1.3" "p.b1.4"
#[2,] "p.b2.1" "p.b2.2" "p.b2.3" "p.b2.4"
#[3,] "p.b3.1" "p.b3.2" "p.b3.3" "p.b3.4"
#[4,] "p.b4.1" "p.b4.2" "p.b4.3" "p.b4.4"
#[5,] "p.b5.1" "p.b5.2" "p.b5.3" "p.b5.4"
#[6,] "p.b6.1" "p.b6.2" "p.b6.3" "p.b6.4"
#[7,] "p.b7.1" "p.b7.2" "p.b7.3" "p.b7.4"

运行1000次以上~1微秒(百万分之一秒)应该足够高效。

microbenchmark::microbenchmark(matrix(m, ncol = 4, byrow = TRUE), times = 1000)
Unit: nanoseconds
                              expr min  lq    mean median   uq  max neval
 matrix(m, ncol = 4, byrow = TRUE) 511 767 967.773    767 1023 7410  1000

答案 1 :(得分:1)

由于m已经是一个矩阵,它足以重新设置dim并转置它:

dim(m) <- c(4,7)
t(m)

     # [,1]     [,2]     [,3]     [,4]    
# [1,] "p.b1.1" "p.b1.2" "p.b1.3" "p.b1.4"
# [2,] "p.b2.1" "p.b2.2" "p.b2.3" "p.b2.4"
# [3,] "p.b3.1" "p.b3.2" "p.b3.3" "p.b3.4"
# [4,] "p.b4.1" "p.b4.2" "p.b4.3" "p.b4.4"
# [5,] "p.b5.1" "p.b5.2" "p.b5.3" "p.b5.4"
# [6,] "p.b6.1" "p.b6.2" "p.b6.3" "p.b6.4"
# [7,] "p.b7.1" "p.b7.2" "p.b7.3" "p.b7.4"

即使m是向量,这也有效,因为在R中,矩阵是具有维度的向量。

要按列填充矩阵,足以提供m维度:

dim(m) <- c(7,4)