Create a list from each matrix column in R

I have a matrix M , and I want to create 3 lists in which each list contains row names of the matrix M , which means for the example for the list fisrt I want to have m[, 1]$a = 1 and m[ ,1]$b = 2 . How can I do this in R for each column?

  m [,1] [,2] [,3] a 1 3 5 b 2 4 6 

I tried this code, but it is not my desire

  > list(m[, 1]) [[1]] ab 1 2 
+6
source share
3 answers

This will create a list of lists:

 apply(M, 2, as.list) 

And if your matrix had code names, they would even be used as the names of your top-level list:

 M <- matrix(1:6, nrow = 2, dimnames = list(c("a", "b"), c("c1", "c2", "c3"))) apply(M, 2, as.list) # $c1 # $c1$a # [1] 1 # # $c1$b # [1] 2 # # # $c2 # $c2$a # [1] 3 # # $c2$b # [1] 4 # # # $c3 # $c3$a # [1] 5 # # $c3$b # [1] 6 
+5
source

Here is the command:

 list.m <- as.list(m[,1]) 
+2
source

Try the following:

 # input matrix m <- matrix(1:6, 2, dimnames = list(c("a", "b"), NULL)) # convert it to a list constructed such that L[, 1]$a gives 1 L <- as.list(m) dim(L) <- dim(m) dimnames(L) <- dimnames(m) 

Now we have:

 > L[, 1]$a [1] 1 
+2
source

Source: https://habr.com/ru/post/944676/


All Articles