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

Time:07-23

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

CodePudding user response:

Try this

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

CodePudding user response:

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"
  • Related