Convert Mixed-Length named List to data.frame

前端 未结 6 1544
夕颜
夕颜 2020-12-31 04:52

I have a list of the following format:

[[1]]
[[1]]$a
[1] 1

[[1]]$b
[1] 3

[[1]]$c
[1] 5

[[2]]       
[[2]]$c
[1] 2

[[2]]$a
[1] 3

There i

6条回答
  •  青春惊慌失措
    2020-12-31 05:22

    Here's my initial thought. It doesn't speed up your approach, but it does simplify the code considerably:

    # makeDF <- function(List, Names) {
    #     m <- t(sapply(List, function(X) unlist(X)[Names], 
    #     as.data.frame(m)
    # }    
    
    ## vapply() is a bit faster than sapply()
    makeDF <- function(List, Names) {
        m <- t(vapply(List, 
                      FUN = function(X) unlist(X)[Names], 
                      FUN.VALUE = numeric(length(Names))))
        as.data.frame(m)
    }
    
    ## Test timing with a 50k-item list
    ll <- createList(50000)
    nms <- c("a", "b", "c")
    
    system.time(makeDF(ll, nms))
    # user  system elapsed 
    # 0.47    0.00    0.47 
    

提交回复
热议问题