简体   繁体   中英

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 ) ) )

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"

Your list m has this structure.

> str(m)
List of 1
 $ a:List of 3
  ..$ b : num [1:2] 1 2
  ..$ c : num 3
  ..$ b1: num 4

As you see, you want to concatenate the names of the top level list with the names of the second level lists. You can achieve this by paste0(names(m), ".", names(m[[1]][1:3])) , or just:

> paste0(names(m), ".", names(m[[1]][]))
[1] "a.b"  "a.c"  "a.b1"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM