[英]How to combine elements from a data list in R?
For instance I have a data list (may have many elements but here only 2): 例如我有一个数据列表(可能有很多元素,但这里只有2个):
> datalist = list(a = matrix(1:10, 5, 2), b = matrix(11:20, 5, 2))
> datalist
$a
[,1] [,2]
[1,] 1 6
[2,] 2 7
[3,] 3 8
[4,] 4 9
[5,] 5 10
$b
[,1] [,2]
[1,] 11 16
[2,] 12 17
[3,] 13 18
[4,] 14 19
[5,] 15 20
I want to combine those two elements a & b into a data frame, say 我想将这两个元素a和b合并到一个数据框中,例如
> dataframe
[,1] [,2]
[1,] 1 6
[2,] 2 7
[3,] 3 8
[4,] 4 9
[5,] 5 10
[6,] 11 16
[7,] 12 17
[8,] 13 18
[9,] 14 19
[10,] 15 20
That is, there are many elements in a data list. 也就是说,数据列表中有许多元素。 All of them have the same columns. 它们都有相同的列。 And I want to combine them into a data frame, such as using "rbind()" function in R. How to do it? 我想将它们组合到一个数据帧中,例如在R中使用“ rbind()”函数。该怎么做? Thanks! 谢谢!
I think you want do.call(rbind, ...)
. 我想你想要do.call(rbind, ...)
do.call(rbind, datalist)
# [,1] [,2]
# [1,] 1 6
# [2,] 2 7
# [3,] 3 8
# [4,] 4 9
# [5,] 5 10
# [6,] 11 16
# [7,] 12 17
# [8,] 13 18
# [9,] 14 19
#[10,] 15 20
Update Sept 16, 2015: A more efficient method for large lists is 2015年9月16日更新:针对大型列表的更有效方法是
data.table::rbindlist(lapply(datalist, as.data.frame))
Easy peasy with plyr
: 使用plyr
轻松轻松:
library(plyr)
datalist = list(a = matrix(1:10, 5, 2), b = matrix(11:20, 5, 2))
dat <- ldply(datalist)
print(dat)
## .id 1 2
## 1 a 1 6
## 2 a 2 7
## 3 a 3 8
## 4 a 4 9
## 5 a 5 10
## 6 b 11 16
## 7 b 12 17
## 8 b 13 18
## 9 b 14 19
## 10 b 15 20
Drop the .id
column if you want/have to. 如果需要,请删除.id
列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.