Extracting data from a list of lists into its own `data.frame` with `purrr`

前端 未结 2 1260
说谎
说谎 2021-01-01 08:03

Representative sample data (list of lists):

l <- list(structure(list(a = -1.54676469632688, b = \"s\", c = \"T\", 
d = structure(list(id = 5L, label = \"U         


        
2条回答
  •  一向
    一向 (楼主)
    2021-01-01 08:15

    For more information on purrr, I recommend Grolemund and Wickham's "R for Data Science" http://r4ds.had.co.nz/

    I think one issue you are facing is that some of the items in l$d are lists of variables with one observation each, ready to be converted to data frames, while other items are lists of such lists.

    But I'm not that good at purrr myself. Here's how I would do it:

    l <- lapply(l, function(x){x$d}) ## work with the data you need.
    
    list_of_observations <- Filter(function(x) {!is.null(names(x))},l)
    
    list_of_lists <- Filter(function(x) {is.null(names(x))}, l)
    
    another_list_of_observations <- unlist(list_of_lists, recursive=FALSE)
    
    df <- lapply(c(list_of_observations, another_list_of_observations),
                 as.data.frame) %>% bind_rows
    

提交回复
热议问题