Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in R Programming by (5.3k points)

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 behavior 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)

)

1 Answer

0 votes
by

To convert a matrix to a list of column-vectors in R, you can use the following functions:

 x <- matrix(1:10,ncol=2)

 split(x, rep(1:ncol(x), each = nrow(x)))

$`1`

[1] 1 2 3 4 5

$`2`

[1]  6  7  8  9 10

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

[[1]]

[1] 1 2 3 4 5

[[2]]

[1]  6  7  8  9 10

Browse Categories

...