transpose nested list

后端 未结 5 1741
误落风尘
误落风尘 2021-01-19 03:27

I have a list structure which represents a table being handed to me like this

> l = list(list(1, 4), list(2, 5), list(3, 6))
> str(l)
List of 3
 $ :Lis         


        
5条回答
  •  鱼传尺愫
    2021-01-19 03:46

    A second base R method using Reduce and split in two lines is

    # bind lists together into a matrix (of lists)
    temp <- Reduce(rbind, l)
    # split unlisted values using indices of columns
    split(unlist(temp), col(temp))
    $`1`
    [1] 1 2 3
    
    $`2`
    [1] 4 5 6
    

    this assumes that each list item has the same number of elements. You can add names in the second line if desired with setNames:

    setNames(split(unlist(temp), col(temp)), c("x", "y"))
    

提交回复
热议问题