Jason
Jason

Reputation: 894

Block-by-Block Matrix Tranpose in R

I have a matrix a of the form:

> a
      [,1] [,2]
 [1,]    1    2
 [2,]    1    2
 [3,]    1    2
 [4,]    3    4
 [5,]    3    4
 [6,]    3    4

I'd like to get the following result:

> aprime
       [,1] [,2] [,3] 
  [1,]    1    1    1 
  [2,]    2    2    2 
  [3,]    3    3    3
  [4,]    4    4    4 

Here is one way to do it:

aprime <- matrix(0, 4, 3)
aprime[1:2, ] <- t(a[1:3, ])
aprime[3:4, ] <- t(a[4:6, ])

However, this is slow, and I'll need to do this operation many times over on very large matrices. Another approach:

aprime <- matrix(t(a), 4, 3)

but that produces

> aprime
      [,1] [,2] [,3]
 [1,]    1    1    3
 [2,]    2    2    4
 [3,]    1    3    3
 [4,]    2    4    4

and finally t(matrix(a, 3, 4))

produces

> aprime
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    3    3    3
[3,]    2    2    2
[4,]    4    4    4

Any thoughts?

Upvotes: 0

Views: 50

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269704

Convert to a 3 dimensional array, permute the dimensions and reshape to a matrix:

matrix(aperm(array(a, c(3, 2, 2)), 3:1), 4)

giving:

     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    2    2    2
[3,]    3    3    3
[4,]    4    4    4

Note: a in reproducible form is:

a <- matrix(c(1, 1, 1, 3, 3, 3, 2, 2, 2, 4, 4, 4), 6)

Upvotes: 1

Related Questions