For instance I have a data list (may have many elements but here only 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
> 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? Thanks!
I think you want 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
data.table::rbindlist(lapply(datalist, as.data.frame))
Easy peasy with 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.