rose
rose

Reputation: 1981

Create list from each column of matrix in 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

Upvotes: 7

Views: 22420

Answers (3)

Guillaume
Guillaume

Reputation: 1286

Here is the command:

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

Upvotes: 3

G. Grothendieck
G. Grothendieck

Reputation: 269421

Try this:

# 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

Upvotes: 2

flodel
flodel

Reputation: 89057

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

Upvotes: 5

Related Questions