Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create list from each column of matrix in R

Tags:

r

I have a matrix M and I want to create 3 lists that each list contains row names of matrix M means that fro examle for the fisrt list, 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 have tried this code, but it's not my desire result

  > list(m[, 1])
  [[1]]
   a b 
   1 2
like image 752
rose Avatar asked May 10 '13 02:05

rose


Video Answer


2 Answers

This will create a list of lists:

apply(M, 2, as.list)

And if your matrix had colnames, those 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
like image 189
flodel Avatar answered Oct 05 '22 05:10

flodel


Here is the command:

list.m <- as.list(m[,1])
like image 26
Guillaume Avatar answered Oct 05 '22 05:10

Guillaume