简体   繁体   中英

Convert matrix to a list of lists

Simple question.

I have a matrix :

my.mat <- matrix(c(1,5,2,6),nrow=2,ncol=2)

Which I want to convert to a list of lists by rows, so the result of the example above is:

my.list <- list(list(1,2),list(5,6))

How do I do it?

Use apply :

apply(my.mat, 1, as.list)

identical(my.list, apply(my.mat, 1, as.list))
#[1] TRUE

You could also use lapply

lapply(1:NROW(my.mat), function(i) lapply(1:NCOL(my.mat), function(j) my.mat[i,j]))

identical(my.list, lapply(1:NROW(my.mat), function(i)
    lapply(1:NCOL(my.mat), function(j)
        my.mat[i,j])))
#[1] TRUE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM