How to simplify this R code to rbind all the tables of a list? [duplicate]


How to simplify this R code to rbind all the tables of a list? [duplicate]



This question already has an answer here:



There must a easy way to rbind all the tables in a list, how to do it?


rbind(tempOut[[1]], tempOut[[2]], tempOut[[3]], tempOut[[4]],
tempOut[[5]], tempOut[[6]], tempOut[[7]], tempOut[[8]],
tempOut[[9]], tempOut[[10]], tempOut[[11]], tempOut[[12]],
tempOut[[13]], tempOut[[14]], tempOut[[15]], tempOut[[16]],
tempOut[[17]], tempOut[[18]], tempOut[[19]], tempOut[[20]],
tempOut[[21]], tempOut[[22]], tempOut[[23]], tempOut[[24]],
tempOut[[25]], tempOut[[26]], tempOut[[27]], tempOut[[28]],
tempOut[[29]], tempOut[[30]], tempOut[[31]], tempOut[[32]])



This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.





You can try dplyr::bind_rows. If you can provide sample data, may be solution can be fine-tuned.
– MKR
Jun 30 at 12:23


dplyr::bind_rows





@MKR Thanks, it works.
– Lee Jim
Jun 30 at 13:51




1 Answer
1



1) do.call Using the first line to provide reproducible test input (where BOD is a builtin 6 row data frame) we use do.call with rbind as shown. No packages are used.


BOD


do.call


rbind


tempOut <- list(BOD, 10*BOD, 100*BOD) # test input

do.call("rbind", tempOut)



giving:


Time demand
1 1 8.3
2 2 10.3
3 3 19.0
4 4 16.0
5 5 15.6
6 7 19.8
7 10 83.0
8 20 103.0
9 30 190.0
10 40 160.0
11 50 156.0
12 70 198.0
13 100 830.0
14 200 1030.0
15 300 1900.0
16 400 1600.0
17 500 1560.0
18 700 1980.0



2) Reduce A second base alternative is:


Reduce("rbind", tempOut)



3) packages There are also some packages which provide this functionality including rbindlist in data.table, bind_rows in dplyr and rbind.fill in plyr.


rbindlist


bind_rows


rbind.fill



3a) purrr::map_dfr Of particular interest if you want to keep track of which table each row came from is the purrr solution -- also note that data.table's rbindlist has an idcol= argument as per @Henrik's comment.


rbindlist


idcol=


library(dplyr) # map_dfr from purrr also requires dplyr
library(purrr)
map_dfr(tempOut, identity, .id = "id")



giving:


id Time demand
1 1 1 8.3
2 1 2 10.3
3 1 3 19.0
4 1 4 16.0
5 1 5 15.6
6 1 7 19.8
7 2 10 83.0
8 2 20 103.0
9 2 30 190.0
10 2 40 160.0
11 2 50 156.0
12 2 70 198.0
13 3 100 830.0
14 3 200 1030.0
15 3 300 1900.0
16 3 400 1600.0
17 3 500 1560.0
18 3 700 1980.0





Regarding "Of particular interest if you want to keep track of which table each row came", data.table::rbindlist has id.col argument, and dplyr::bind_rows has .id argument.
– Henrik
Jun 30 at 12:53



data.table::rbindlist


id.col


dplyr::bind_rows


.id

Popular posts from this blog

How to input without newline? (Python)

C++ thread error: no type named ‘type’ MINGW

Analog for TagView in flutter