Revert list structure

前端 未结 6 769
梦如初夏
梦如初夏 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:02

    How about this simple solution, which is completely general, and almost as fast as Josh O'Brien's original answer that assumed common internal names (#4).

    zv <- unlist(unname(z), recursive=FALSE)
    ans <- split(setNames(zv, rep(names(z), lengths(z))), names(zv))
    

    And here is a general version that is robust to not having names:

    invertList <- function(z) {
        zv <- unlist(unname(z), recursive=FALSE)
        zind <- if (is.null(names(zv))) sequence(lengths(z)) else names(zv)
        if (!is.null(names(z)))
            zv <- setNames(zv, rep(names(z), lengths(z)))
        ans <- split(zv, zind)
        if (is.null(names(zv))) 
            ans <- unname(ans)
        ans
    }
    

提交回复
热议问题