Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

r - R-递归查找子列表数(R - Recursively find number of sub lists)

I have a list of lists (let's call the main/parent list A).

(我有一个列表列表(我们称其为主/父列表A)。)

The number of sub-lists in list A varies: A[[1]] could have 1 sub-list, whereas A[[14344]] could have 6 sub-lists.

(列表A中子列表的数量各不相同:A [[1]]可以有1个子列表,而A [[14344]]可以有6个子列表。)

I need to find the number of sub-lists for each element of A. The goal is to find or write a function that will return A[1] = 1 and A[14344] = 6 .

(我需要找到A的每个元素的子列表数。目标是找到或编写一个将返回A[1] = 1A[14344] = 6 。)

Using length or lengths alone doesn't work for me -- see the example below:

(使用lengthlengths单独对我不起作用-见下面的例子:)

A[1] # element 1 of list A contains 1 sub-list with 5 values
   [,1]
[1,]    1
[2,]    1
[3,]    1
[4,]    1
[5,]    1


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,]    1
[2,]    1
[3,]    1
[4,]    1
[5,]    1

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

For the example above, I need something that gives A[1] = 1 and A[2] = 5 .

(对于上面的示例,我需要提供A[1] = 1A[2] = 5 。)

Any thoughts?

(有什么想法吗?)

  ask by GeoCat333 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Maybe you can use lengths

(也许你可以使用lengths)

lengths(A)

For example, for this list

(例如,对于此列表)

A <- list(a = 1, b = c(1, 2, 34))
out <- lengths(A)
out
#a b 
#1 3 

So out[[1]] returns 1 and out[[2]] returns 3.

(因此out[[1]]返回1, out[[2]]返回3。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...