Revert list structure

前端 未结 6 770
梦如初夏
梦如初夏 2020-12-24 02:26

GOAL

Given a list of lists my goal is to reverse its structure (R language).

So, I want to bring the elements of the nested lists to be el

6条回答
  •  忘掉有多难
    2020-12-24 03:08


    EDIT -- working from @Josh O'Briens suggestion and my own improvemes

    The problem was that do.call rbind was not calling rbind.data.frame which does some matching of names. rbind.data.frame should work, because data.frames are lists and each sublist is a list, so we could just call it directly.

    apply(do.call(rbind.data.frame, z), 1, as.list)
    

    However, while this may be succicint, it is slow because do.call(rbind.data.frame, ...) is inherently slow.


    Something like (in two steps)

     # convert each component of z to a data.frame
     # so rbind.data.frame so named elements are matched
     x <- data.frame((do.call(rbind, lapply(z, data.frame))))
     # convert each column into an appropriately named list
     o <- lapply(as.list(x), function(i,nam) as.list(`names<-`(i, nam)), nam = rownames(x))
     o
    $a
    $a$z1
    [1] 1
    
    $a$z2
    [1] 1
    
    
    $b
    $b$z1
    [1] 2
    
    $b$z2
    [1] 4
    
    
    $c
    $c$z1
    [1] 3
    
    $c$z2
    [1] 0
    

    And an alternative

    # unique names
    nn <- Reduce(unique,lapply(z, names))
    # convert from matrix to list `[` used to ensure correct ordering
    as.list(data.frame(do.call(rbind,lapply(z, `[`, nn))))
    

提交回复
热议问题