2013-06-12 46 views
7

我有載體列表,像這樣:如何列表轉換成一個矩陣R中

[[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 

我要將列表轉換成每個向量的內容與相關的矩陣在雙括號中列出索引號。

例子:

 [,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 
+0

請儘量使用一致的術語。你的問題標題要求'data.frame',但你的問題要求'矩陣'。 – A5C1D2H2I1M1N2O1R2T1

+0

你已經有了很多答案,但也檢查我的原因'熔化'是非常有用的,或者因爲它的靈活性作爲輸入'data.frame','array'和'list',以及幾個「熔化」選項,你可以有不同的參數。 – Michele

回答

9

您可以使用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)) 
2

如果l是你原來的列表:

cbind(rep(seq_along(l), times=sapply(l, length)), unlist(l)) 
7
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