R (purrr) flatten list of named lists to list and keep names

前端 未结 1 949
别跟我提以往
别跟我提以往 2021-01-19 08:26

Maybe I\'m missing something obvious but trying to flatten a list of named lists of named lists in R (may even be more nested) into eventually one flat list. purrr

相关标签:
1条回答
  • 2021-01-19 09:01

    I looked at the source for rlist::list.flatten() and copied the source into a new function to avoid that dependency.

    my_flatten <- function (x, use.names = TRUE, classes = "ANY") 
    {
      #' Source taken from rlist::list.flatten
      len <- sum(rapply(x, function(x) 1L, classes = classes))
      y <- vector("list", len)
      i <- 0L
      items <- rapply(x, function(x) {
        i <<- i + 1L
        y[[i]] <<- x
        TRUE
      }, classes = classes)
      if (use.names && !is.null(nm <- names(items))) 
        names(y) <- nm
      y
    }
    
    alist <- list(list1 = list(a = 1, b = 2, blist = list(a = 3, b = 4)),
                  list2 = list(a = 1, b = 2, blist = list(a = 3, b = 4)))
    
    
    flat_list <- my_flatten(alist)
    
    str(flat_list)
    

    Result:

    List of 8
     $ list1.a      : num 1
     $ list1.b      : num 2
     $ list1.blist.a: num 3
     $ list1.blist.b: num 4
     $ list2.a      : num 1
     $ list2.b      : num 2
     $ list2.blist.a: num 3
     $ list2.blist.b: num 4
    
    0 讨论(0)
提交回复
热议问题