transpose nested list

后端 未结 5 1742
误落风尘
误落风尘 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:51

    For the specific example, you can use this pretty simple approach:

    split(unlist(l), c("x", "y"))
    #$x
    #[1] 1 2 3
    #
    #$y
    #[1] 4 5 6
    

    It recycles the x-y vector and splits on that.


    To generalize this to "n" elements in each list, you can use:

    l = list(list(1, 4, 5), list(2, 5, 5), list(3, 6, 5)) # larger test case
    
    split(unlist(l, use.names = FALSE), paste0("x", seq_len(length(l[[1L]]))))
    # $x1
    # [1] 1 2 3
    # 
    # $x2
    # [1] 4 5 6
    # 
    # $x3
    # [1] 5 5 5
    

    This assumes, that all the list elements on the top-level of l have the same length, as in your example.

提交回复
热议问题