0

Trivial question I imagine..

I have an M by N matrix. For example:

   mat <- matrix(data = rnorm(12), nrow = 3, ncol = 4)

and I would like to convert it to an array of M vectors each of length N (meaning an array where each of the vectors is a row in the matrix).

Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
user1701545
  • 5,706
  • 14
  • 49
  • 80
  • 2
    I'm going to go out on a limb and guess that when you say "array" you really mean "list". Because in R a matrix is just a special case of an array that happens to have only two dimensions. – joran Oct 28 '14 at 21:11
  • If this _is_ what you mean, then the post seems to be [a duplicate](http://stackoverflow.com/q/6819804/489704). – jbaums Oct 28 '14 at 22:07

2 Answers2

6

I'm going to go with @joran and also presume that you mean you want a list, and not an array. So to split a matrix by its rows, you can use split with row

split(mat, row(mat))
# $`1`
# [1]  0.4583610 -2.2781416 -1.5936889  0.6746935
#
# $`2`
# [1]  1.3758054  0.3980531  1.0167698 -0.7905586
#
# $`3`
# [1]  1.3177040 -1.5425623  0.2905337  0.4275807

Similarly, to split by the columns you can do split(mat, col(mat))

Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
  • (+1) Beautiful in its simplicity. This ugly (by comparison) beast (`lapply(seq_len(nrow(m)), function(i) m[i,])`) is quite a bit faster for big matrices, as mentioned in [this post](http://stackoverflow.com/a/6821395/489704). – jbaums Oct 28 '14 at 22:06
4

Are you looking for t to transpose your matrix?

mat <- matrix(data = rnorm(12), nrow = 3, ncol = 4)
mat
#          [,1]       [,2]        [,3]       [,4]
#[1,] 0.9577888 -0.6362354 -0.02213621 -0.1537499
#[2,] 2.2317189 -0.2593682  0.67468979 -2.2123352
#[3,] 0.8379689 -0.3452324  0.66811564 -1.9828007
t(mat)
#            [,1]       [,2]       [,3]
#[1,]  0.95778884  2.2317189  0.8379689
#[2,] -0.63623540 -0.2593682 -0.3452324
#[3,] -0.02213621  0.6746898  0.6681156
#[4,] -0.15374989 -2.2123352 -1.9828007
sgibb
  • 25,396
  • 3
  • 68
  • 74