Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a matrix to a list of column-vectors in R?

Tags:

list

r

matrix

Say you want to convert a matrix to a list, where each element of the list contains one column. list() or as.list() obviously won't work, and until now I use a hack using the behaviour of tapply :

x <- matrix(1:10,ncol=2)  tapply(x,rep(1:ncol(x),each=nrow(x)),function(i)i) 

I'm not completely happy with this. Anybody knows a cleaner method I'm overlooking?

(for making a list filled with the rows, the code can obviously be changed to :

tapply(x,rep(1:nrow(x),ncol(x)),function(i)i) 

)

like image 940
Joris Meys Avatar asked Jul 25 '11 17:07

Joris Meys


People also ask

How do I turn a matrix into a list in R?

The as. list() is an inbuilt function that takes an R language object as an argument and converts the object into a list. We have used this function to convert our matrix to a list. These objects can be Vectors, Matrices, Factors, and data frames.

How do I convert a matrix to an array in R?

Functions Used data-is the input vector which becomes the data elements of the matrix. nrow-is the numbers of rows to be created. ncol-is the numbers of columns to be created. byrow-is a logical clue,if it is true then input vector elements are arranged by row.

How do you convert a matrix to a vector?

Conversion of a Matrix into a Row Vector. This conversion can be done using reshape() function along with the Transpose operation. This reshape() function is used to reshape the specified matrix using the given size vector.


2 Answers

Gavin's answer is simple and elegant. But if there are many columns, a much faster solution would be:

lapply(seq_len(ncol(x)), function(i) x[,i]) 

The speed difference is 6x in the example below:

> x <- matrix(1:1e6, 10) > system.time( as.list(data.frame(x)) )    user  system elapsed     1.24    0.00    1.22  > system.time( lapply(seq_len(ncol(x)), function(i) x[,i]) )    user  system elapsed      0.2     0.0     0.2  
like image 85
Tommy Avatar answered Oct 06 '22 10:10

Tommy


In the interests of skinning the cat, treat the array as a vector as if it had no dim attribute:

 split(x, rep(1:ncol(x), each = nrow(x))) 
like image 32
mdsumner Avatar answered Oct 06 '22 10:10

mdsumner