【问题标题】:How to simplify this R code to rbind all the tables of a list? [duplicate]如何简化此 R 代码以 rbind 列表的所有表? [复制]
【发布时间】:2018-12-09 10:07:36
【问题描述】:

必须有一个简单的方法来rbind列表中的所有表,怎么做?

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]])

【问题讨论】:

  • 你可以试试dplyr::bind_rows。如果你能提供样本数据,可能是可以微调的解决方案。
  • @MKR 谢谢,它有效。

标签: r list rbind


【解决方案1】:

1) do.call 使用第一行提供可重现的测试输入(其中BOD 是内置的6 行数据框),我们使用do.callrbind,如图所示。不使用任何包。

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

do.call("rbind", tempOut)

给予:

   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("rbind", tempOut)

3) 包 还有一些包提供此功能,包括data.table 中的rbindlist、dplyr 中的bind_rows 和plyr 中的rbind.fill

3a) purrr::map_dfr 如果您想跟踪每行来自哪个表,则特别感兴趣的是 purrr 解决方案 - 另请注意 data.table 的 rbindlist 有一个 @ 987654331@ 参数根据@Henrik 的评论。

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

给予:

   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

【讨论】:

  • 关于“如果您想跟踪每行来自哪个表的特别感兴趣”,data.table::rbindlistid.col 参数,dplyr::bind_rows 有 @987654337 @参数。
猜你喜欢
  • 2018-10-24
  • 2021-08-21
  • 2019-08-01
  • 2015-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多