kin182
kin182

Reputation: 403

How to convert a matrix to lists in R?

I have seen a lot of questions on how to convert lists to a matrix. However, I would like to convert a matrix to lists.

For example,

mdat <- matrix(c(1,2,3, 11,12,13), nrow = 2, ncol = 3, byrow = TRUE,
               dimnames = list(c("row1", "row2"),
                               c("C.1", "C.2", "C.3")))

mdat
         C.1 C.2 C.3
   row1   1   2   3
   row2  11  12  13

I wanted to convert it to something like this:

$C.1
      C.1
row1   1
row2  11

$C.2
      C.2
row1   2
row2  12

$C.3
     C.3
row1   3
row2  13

I tried this one but it did not work:

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

 $`1`
 [1]  1 11

 $`2`
 [1]  2 12

 $`3`
 [1]  3 13

Could anyone help? Thanks!

Upvotes: 1

Views: 47

Answers (1)

akrun
akrun

Reputation: 887981

We can use

lapply(split.default(as.data.frame(mdat), colnames(mdat)), as.matrix)
#$C.1
#     C.1
#row1   1
#row2  11

#$C.2
#     C.2
#row1   2
#row2  12

#$C.3
#     C.3
#row1   3
#row2  13

Upvotes: 2

Related Questions