0

Within R I would like to transform an array (dimensions: i, j, k) into a matrix such that the observations (i.e. rows) of the new matrix are each element from the array pulled k "layers" at a time. Essentially, again, the rows of the new matrix will be composed of each element of the previous array with the columns of the matrix being equivalent to the k dimension of the array. Thus, the new matrix should be composed of i*j rows with k columns.

Please let me know if I can clarify or provide an example of input / output!

Thanks!

Edit: This code works (but is not optimized) —

    m = array(1:27,dim = c(3,3,3))
    m
    dim = dim(m)
    mparam = dim[3]

    listm = list()
    for (i in 1:mparam){
      listm[[i]] = as.vector(m[,,i])
    }

    untran = do.call(rbind,listm)
    transposed = t(untran)
    transposed
  • 2
    Yes, please do provide a minimal example of input and desired output. People are generally much more happy to help with a small 'copy/paste example' to play with, and it is much easier to understand exactly what you want. See e.g. [**here**](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610) Cheers. – Henrik Feb 24 '14 at 19:32
  • By the way, I agree with Henrik. I may have been able to correctly guess what you wanted this time, but it was just a guess. I answered half expecting to have to delete my answer, since you hadn't provided an example. Please do so in the future. – joran Feb 24 '14 at 19:55

1 Answers1

2

Like this?

m <- array(1:27,dim = c(3,3,3))
> m
, , 1

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

, , 2

     [,1] [,2] [,3]
[1,]   10   13   16
[2,]   11   14   17
[3,]   12   15   18

, , 3

     [,1] [,2] [,3]
[1,]   19   22   25
[2,]   20   23   26
[3,]   21   24   27

> matrix(m,9,3)
      [,1] [,2] [,3]
 [1,]    1   10   19
 [2,]    2   11   20
 [3,]    3   12   21
 [4,]    4   13   22
 [5,]    5   14   23
 [6,]    6   15   24
 [7,]    7   16   25
 [8,]    8   17   26
 [9,]    9   18   27
joran
  • 169,992
  • 32
  • 429
  • 468
  • You don't actually need the third argument to `matrix` -- after all, if the dimensions don't match up, `R` will recycle with a warning. – Carl Witthoft Feb 24 '14 at 20:48
  • @CarlWitthoft True. I always type both dimensions because I'm just a dumb human and it makes it easier for me to read. :) – joran Feb 24 '14 at 20:52
  • @joran Yes, that's exactly what I need! And yes, I should have provided sample and desired input/output. I actually wrote the example code (displayed above) before your post — not knowing that the single matrix() function would do everything I need. :-) Thanks! – Devin Routh Feb 25 '14 at 21:00