What is the most efficient way to cast a list as a data frame?

前端 未结 7 858
悲&欢浪女
悲&欢浪女 2020-11-29 16:55

Very often I want to convert a list wherein each index has identical element types to a data frame. For example, I may have a list:

> my.list
[[1]]
[[1]]         


        
7条回答
  •  攒了一身酷
    2020-11-29 17:24

    Although this question has long since been answered, it's worth pointing out the data.table package has rbindlist which accomplishes this task very quickly:

    library(microbenchmark)
    library(data.table)
    l <- replicate(1E4, list(a=runif(1), b=runif(1), c=runif(1)), simplify=FALSE)
    
    microbenchmark( times=5,
      R=as.data.frame(Map(f(l), names(l[[1]]))),
      dt=data.frame(rbindlist(l))
    )
    

    gives me

    Unit: milliseconds
     expr       min        lq    median        uq       max neval
        R 31.060119 31.403943 32.278537 32.370004 33.932700     5
       dt  2.271059  2.273157  2.600976  2.635001  2.729421     5
    

提交回复
热议问题