12

Suppose I have a matrix foo as follows:

foo <- cbind(c(1,2,3), c(15,16,17))

> foo
     [,1] [,2]
[1,]    1   15
[2,]    2   16
[3,]    3   17

I'd like to turn it into a list that looks like

[[1]]
[1]  1 15

[[2]]
[1]  2 16

[[3]]
[1]  3 17

You can do it as follows:

lapply(apply(foo, 1, function(x) list(c(x[1], x[2]))), function(y) unlist(y))

I'm interested in an alternative method that isn't as complicated. Note, if you just do apply(foo, 1, function(x) list(c(x[1], x[2]))), it returns a list within a list, which I'm hoping to avoid.

andrewj
  • 2,965
  • 8
  • 36
  • 37
  • See this question with more answers: https://stackoverflow.com/questions/6819804/convert-a-matrix-to-a-list-of-column-vectors – Maël May 05 '23 at 15:11

3 Answers3

20

Here's a cleaner solution:

as.list(data.frame(t(foo)))

That takes advantage of the fact that a data frame is really just a list of equal length vectors (while a matrix is really a vector that is displayed with columns and rows...you can see this by calling foo[5], for instance).

You could also do this, although it isn't much of an improvement:

lapply(1:nrow(foo), function(i) foo[i,])
Shane
  • 98,550
  • 35
  • 224
  • 217
6
library(plyr)
alply(foo, 1)
hadley
  • 102,019
  • 32
  • 183
  • 245
1

You can use asplit to split a matrix into a list.

asplit(foo, 1)
#[[1]]
#[1]  1 15
#
#[[2]]
#[1]  2 16
#
#[[3]]
#[1]  3 17
GKi
  • 37,245
  • 2
  • 26
  • 48