简体   繁体   English

提取深层嵌套列表的名称

[英]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. 我想获取m的名称并保持水平。

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. 同样, unlist()对于大的嵌套列表来说也是一项昂贵的操作。 Is there any way to do it without unlist() and in a faster way ? 有没有办法不用unlist()并以更快的方式做到这一点?

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: 对于OP的第二个输入,将产生:

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. 您的列表m具有此结构。

> 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:3]))或仅通过paste0(names(m), ".", names(m[[1]][1:3]))方式实现此paste0(names(m), ".", names(m[[1]][1:3]))

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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