且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

转置嵌套列表

更新时间:2023-11-18 19:07:16

对于特定示例,您可以使用以下非常简单的方法:

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

它回收x-y向量并对其进行分割.

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

要将其概括为每个列表中的"n"个元素,可以使用:

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

这假定l顶层的所有列表元素的长度都与您的示例相同.

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