【发布时间】:2019-12-01 04:42:03
【问题描述】:
我有一个列表列表(我们称之为主/父列表 A)。列表 A 中的子列表数量不同:A[[1]] 可以有 1 个子列表,而 A[[14344]] 可以有 6 个子列表。我需要找到 A 的每个元素的子列表的数量。目标是找到或编写一个返回 A[1] = 1 和 A[14344] = 6 的函数。
单独使用 length 或 lengths 对我不起作用 - 请参阅下面的示例:
A[1] # element 1 of list A contains 1 sub-list with 5 values
[,1]
[1,] 2
[2,] 3
[3,] 4
[4,] 5
[5,] 6
A[2] # element 2 of list A contains 5 sub-lists with 5,2,2,3,4 values (respectively)
[[1]]
[[1]][[1]]
[1] 2 3 4 5 6
[[1]][[2]]
[1] 15 16
[[1]][[3]]
[1] 18 19
[[1]][[4]]
[1] 23 24 25
[[1]][[5]]
[1] 30 31 32 33
# using lengths() returns the entire list for A[1] and the length of each element in list 2
lengths(A[[1]]))
[,1]
[1,] 2
[2,] 3
[3,] 4
[4,] 5
[5,] 6
lengths(A[[2]])
[1] 5 2 2 3 4
# using length returns just 1 for both
length(A[1])
[1] 1
length(A[2])
[1] 1
# structure of sub-list 1
str(A[1])
List of 1
$ : int [1:5, 1] 2 3 4 5 6
# structure of sub-list 2
str(A[2])
List of 1
$ :List of 5
..$ : int [1:5] 2 3 4 5 6
..$ : int [1:2] 15 16
..$ : int [1:2] 18 19
..$ : int [1:3] 23 24 25
..$ : int [1:4] 30 31 32 33
对于上面的示例,我需要提供A[1] = 1 和A[2] = 5 的东西。有什么想法吗?
【问题讨论】: