1

What is the most elegant way of converting a matrix to a list, where each element of the list is a vector containing the elements in a row of the matrix?

eye_mew
  • 8,855
  • 7
  • 30
  • 50

2 Answers2

6

A couple of approaches

Assuming your matrix is called foo

lapply(seq_len(nrow(foo)), function(x) foo[x,])

or less efficiently.

lapply(apply(foo,1,list), unlist)

mnel
  • 113,303
  • 27
  • 265
  • 254
3

Just for the fun of it, here's the shortest syntax I could think of:

split(x, 1:nrow(x))

Or using the plyr package:

aaply(x, 1, list)

These are slower than @mnel's solutions though (especially the aaply() one).

Ciarán Tobin
  • 7,306
  • 1
  • 29
  • 45