必承其重 | 欲带皇冠 2010-05-17 17:38 采纳率: 0%
浏览 268
已采纳

将数据帧列表转换为一个数据帧

I have code that at one place ends up with a list of data frames which I really want to convert to a single big data frame.

I got some pointers from an earlier question which was trying to do something similar but more complex.

Here's an example of what I am starting with (this is grossly simplified for illustration):

listOfDataFrames <- vector(mode = "list", length = 100)

for (i in 1:100) {
    listOfDataFrames[[i]] <- data.frame(a=sample(letters, 500, rep=T),
                             b=rnorm(500), c=rnorm(500))
}

I am currently using this:

  df <- do.call("rbind", listOfDataFrames)

转载于:https://stackoverflow.com/questions/2851327/convert-a-list-of-data-frames-into-one-data-frame

  • 写回答

8条回答 默认 最新

  • 七度&光 2010-05-17 17:54
    关注

    One other option is to use a plyr function:

    df <- ldply(listOfDataFrames, data.frame)
    

    This is a little slower than the original:

    > system.time({ df <- do.call("rbind", listOfDataFrames) })
       user  system elapsed 
       0.25    0.00    0.25 
    > system.time({ df2 <- ldply(listOfDataFrames, data.frame) })
       user  system elapsed 
       0.30    0.00    0.29
    > identical(df, df2)
    [1] TRUE
    

    My guess is that using do.call("rbind", ...) is going to be the fastest approach that you will find unless you can do something like (a) use a matrices instead of a data.frames and (b) preallocate the final matrix and assign to it rather than growing it.

    Edit 1:

    Based on Hadley's comment, here's the latest version of rbind.fill from CRAN:

    > system.time({ df3 <- rbind.fill(listOfDataFrames) })
       user  system elapsed 
       0.24    0.00    0.23 
    > identical(df, df3)
    [1] TRUE
    

    This is easier than rbind, and marginally faster (these timings hold up over multiple runs). And as far as I understand it, the version of plyr on github is even faster than this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度