Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - Extract names of deeply nested lists

Suppose I have a list like this :

m <- list('a' = list('b' = c(1, 2), 'c' = 3, 'b1' = 4))

I want to get the names of m and maintain the levels also.

If I do

names(unlist(m))

It gives output

"a.b1" "a.b2" "a.c"  "a.b1"

But I want only names like

"a.b" "a.c" "a.b1"

How to get that ?

Also unlist() is a costly operation for big nested lists. Is there any way to do it without unlist() and in a faster way ?

Example 2 : 

p = list( 'a' = list( 'z' = c( 1, 2 ), 'g' = list( 'i' = 2, 'j' = 3 ) ), 'd'    = list( 'k' = c( 4, 5 ) ) )

Example 3 :

p = list( 'a' = list( 'z' = c( 1, 2 ), 'g' = list( 2, 3 ) ), 'd' = list( 'k' = c( 4, 5 ) ) )
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can get there by recursively extracting only the first element of each vector in the list and getting the names of that structure:

names(rapply(m, function(x) head(x, 1)))
#[1] "a.b"  "a.c"  "a.b1"

Here's an example with a more complex input-list:

m <- list(a=list(b=c(1, 2), c=3, b1=list(x=1, y=2:4)), x=list(a=1,b=2), c=4:8)
str(m)
# List of 3
# $ a:List of 3
# ..$ b : num [1:2] 1 2
# ..$ c : num 3
# ..$ b1:List of 2
# .. ..$ x: num 1
# .. ..$ y: int [1:3] 2 3 4
# $ x:List of 2
# ..$ a: num 1
# ..$ b: num 2
# $ c: int [1:5] 4 5 6 7 8

names(rapply(m, function(x) head(x, 1)))
#[1] "a.b"    "a.c"    "a.b1.x" "a.b1.y" "x.a"    "x.b"    "c" 

For OP's second input, this yields:

p <- list('a' = list('z' = c(1, 2), 'g' = list('i' = 2, 'j' = 3)), 'd' = list('k' = c(4, 5)))
names(rapply(p, function(x) head(x, 1)))
#[1] "a.z"   "a.g.i" "a.g.j" "d.k"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...