5

I have a matrix:

R> pippo.m
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    5    6    7    8
[3,]    9   10   11   12
[4,]   13   14   15   16
[5,]   17   18   19   20
[6,]   21   22   23   24

and I would like to transform this matrix in a 3D array with dim=(2,4,3). Passing through the transponse of pippo.m I am able to obtain a similar result but with columns and rows rotated.

> pippo.t <- t(pippo.m)

> pippo.vec <- as.vector(pippo.t)

> pippo.arr <- array(pippo.vec,dim=c(4,2,3),dimnames=NULL)

> pippo.arr
 , , 1
     [,1] [,2]
 [1,]    1    5
 [2,]    2    6
 [3,]    3    7
 [4,]    4    8

 , , 2
     [,1] [,2]
[1,]    9   13
[2,]   10   14
[3,]   11   15
[4,]   12   16

, , 3
     [,1] [,2]
[1,]   17   21
[2,]   18   22
[3,]   19   23
[4,]   20   24

Actually, I would prefer to mantain the same distribution of the original data, as rows and colums represent longitude and latitude and the third dimension is time. So I would like to obtain something like this:

pippo.a 
, , 1
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    5    6    7    8


, , 2
     [,1] [,2] [,3] [,4]
[1,]    9   10   11   12
[2,]   13   14   15   16


, , 3
     [,1] [,2] [,3] [,4]
[1,]   17   18   19   20
[2,]   21   22   23   24

How can I do?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Corrado
  • 157
  • 4
  • 9

1 Answers1

6

Behold the magic of aperm!

m <- matrix(1:24,6,4,byrow = TRUE)
> aperm(array(t(m),c(4,2,3)),c(2,1,3))
, , 1

     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    5    6    7    8

, , 2

     [,1] [,2] [,3] [,4]
[1,]    9   10   11   12
[2,]   13   14   15   16

, , 3

     [,1] [,2] [,3] [,4]
[1,]   17   18   19   20
[2,]   21   22   23   24
Richard D
  • 327
  • 3
  • 16
joran
  • 169,992
  • 32
  • 429
  • 468
  • 3
    or without transpose, `aperm(array(m, c(2, 3, 4)), c(1,3,2))`. This thing feels like a rubik's cube... – flodel Jul 20 '12 at 17:15