Convert a matrix to a list of column-vectors

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 

Leave a Comment