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

前端 未结 7 840
悲&欢浪女
悲&欢浪女 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:38

    This

    f = function(x) function(i) sapply(x, `[[`, i)
    

    is a function that returns a function that extracts the i'th element of x. So

    Map(f(mylist), names(mylist[[1]]))
    

    gets a named (thanks Map!) list of vectors that can be made into a data frame

    as.data.frame(Map(f(mylist), names(mylist[[1]])))
    

    For speed it's usually faster to use unlist(lapply(...), use.names=FALSE) as

    f = function(x) function(i) unlist(lapply(x, `[[`, i), use.names=FALSE)
    

    A more general variant is

    f = function(X, FUN) function(...) sapply(X, FUN, ...)
    

    When do the list-of-lists structures come up? Maybe there's an earlier step where an iteration could be replaced by something more vectorized?

    0 讨论(0)
提交回复
热议问题