Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting a matrix to a list

Tags:

list

r

matrix

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.

like image 454
andrewj Avatar asked Mar 18 '10 15:03

andrewj


People also ask

How do you change a matrix into a list?

To convert Matrix to List in R, use the split() function. The split() is an inbuilt R function that divides the data in the vector into the groups defined by f. The replacement forms replace values corresponding to such a division. The unsplit() function reverses the effect of the split.

How do you change a matrix into a list in Python?

With NumPy, [ np. array ] objects can be converted to a list with the tolist() function.

How do I convert a matrix to a list in R?

By default, as. list() converts the matrix to a list of lists in column-major order. Therefore, we have to use unlist() function to convert the list of lists to a single list. unlist() function in R Language is used to convert a list of lists to a single list, by preserving all the components.


2 Answers

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,])
like image 130
Shane Avatar answered Sep 22 '22 06:09

Shane


library(plyr)
alply(foo, 1)
like image 44
hadley Avatar answered Sep 23 '22 06:09

hadley