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?
Asked
Active
Viewed 925 times
2 Answers
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
-
1or alply(foo, 1) would do it – mdsumner May 13 '13 at 09:44
-
Nice. Seems to be faster too. Still way slower than using `lapply()` though (or even `split()`). – Ciarán Tobin May 13 '13 at 10:03