[英]How to convert a list into a matrix in R
I do have a list of vectors, like this: 我有一个矢量列表,像这样:
[[1]]
[1] 1 2 7 9 10 13 14 15 20
[[2]]
[1] 3 4 5 6
[[3]]
[1] 8 11 12
[[4]]
[1] 16 17 18 19
[[5]]
[1] 21 22 23
I want to convert the list to a matrix where the contents of each vector are associated with the list index number in double brackets. 我想将列表转换为矩阵,其中每个向量的内容与双括号中的列表索引号相关联。
Example: 例:
[,1] [,2]
[1,] 1 1
[2,] 1 2
[3,] 1 7
[4,] 1 9
[5,] 1 10
[6,] 1 13
[7,] 1 14
[8,] 1 15
[9,] 1 20
[10,] 2 3
[11,] 2 4
[12,] 2 5
[13,] 2 6
[14,] 3 8
[15,] 3 11
[16,] 3 12
[17,] 4 16
[18,] 4 17
[19,] 4 18
[20,] 4 19
[21,] 5 21
[22,] 5 22
[23,] 5 23
You can use unlist
to get the values in the list, then use sapply
to get the number of values in each element of the list. 您可以使用
unlist
获取列表中的值,然后使用sapply
获取列表中每个元素的值数。
# Generate the list
a <- list(1:10, 20:30, 40:45)
# Find the number of elements
num.el <- sapply(a, length)
# Generate the matrix
res <- cbind(unlist(a), rep(1:length(a), num.el))
library(reshape2)
lst <- list(c(1:3), c(11:12), c(22))
> melt(lst)
value L1
1 1 1
2 2 1
3 3 1
4 11 2
5 12 2
6 22 3
如果l
是您的原始列表:
cbind(rep(seq_along(l), times=sapply(l, length)), unlist(l))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.