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
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
Here is the command:
list.m <- as.list(m[,1])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With