简体   繁体   中英

R recursively get the name of the first element of a nested list of arbitrary depth

I know there are plenty of related posts, but I found none of them that solved my issue. The situation is the following: I am using the shinyTree package and when I select a node, its structure is the following

List of 1
 $ :List of 1
  ..$ ParentA:List of 1
  .. ..$ ParentB:List of 1
  .. .. ..$ ParentC: num 0

this can be reproduced:

mynode = list(list(ParentA=list(ParentB=list(ParentC=0)))

I would like to obtain from this a vector of the names of the nested list

c("ParentA", "ParentB", "ParentC")

I have tried to use recursive functions like

recursive <- function(x){
if(is.list(x)) recursive(x[[1]])
names(x[[1]])
}

with lapply but it did not work... I have no more ideas what to try... Could anyone help please??

Thanks in advance

Try this

strsplit(names(unlist(mynode)) , "\\.")[[1]]
  • output
#> [1] "ParentA" "ParentB" "ParentC"

The recursive solution would be:

recursive <- function(node) {
  x <- NULL
  if (is.list(node)) {
    first <- node[[1]]
    x <- c(x, names(first)[[1]], recursive(first))
  }
  
  return(x)
}

recursive(mynode)
#> [1] "ParentA" "ParentB" "ParentC"

Upsides? It won't fail regardless of the format of the names, especially if they have "." eg. ParentA.A .

mynode <- list(list(ParentA.A=list(ParentB=list(ParentC=0))))

strsplit() would not give you the right answer here:

strsplit(names(unlist(mynode)) , "\\.")[[1]]
#> [1] "ParentA" "A"       "ParentB" "ParentC"

But the recursive solution would work just fine:

recursive(mynode)
#> [1] "ParentA.A" "ParentB"   "ParentC"

This can also be done with rrapply() in the rrapply -package, which may be useful to handle multiple nodes in the nested list simultaneously.

rrapply::rrapply(
  mynode, 
  f = function(x, .xparents) .xparents[-1],  
  how = "flatten"                      
)
#> $ParentC
#> [1] "ParentA" "ParentB" "ParentC"

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