converting a matrix to a list

Posted by andrewj on Stack Overflow See other posts from Stack Overflow or by andrewj
Published on 2010-03-18T15:45:58Z Indexed on 2010/03/18 19:51 UTC
Read the original article Hit count: 408

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about r

    Related posts about list