rnorouzian
rnorouzian

Reputation: 7517

Change matrix dimensions and fill it by Row

In R, I was wondering how I can restructure the following Matrix:

From:

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"))

To:

       [,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"`

Upvotes: 1

Views: 707

Answers (2)

989
989

Reputation: 12937

Since m is already a matrix, its enough to re-set the dim and transpose it:

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"

This works even if m was a vector since in R, a matrix is a vector with dimensions.

To fill in the matrix column-wise, its enough to give m the dimensions:

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

Upvotes: 1

LyzandeR
LyzandeR

Reputation: 37879

Running the following should do the trick:

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"

And ~1 microsecond (1 millionth of a second) for running the above 1000 times should be efficient enough.

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

Upvotes: 2

Related Questions