user36302
user36302

Reputation: 380

names of leaves of nested list in R

I want to check if two nested lists have the same names at the last level.

If unlist gave an option not to concatenate names this would be trivial. However, it looks like I need some function leaf.names():

X <- list(list(a = pi, b = list(alpha.c = 1:5, 7.12)), d = "a test")

leaf.names(X)
[1] "a" "alpha.c" "NA" "d"

I want to avoid any inelegant grepping if possible. I feel like there should be some easy way to do this with rapply or unlist...

Upvotes: 0

Views: 182

Answers (1)

IceCreamToucan
IceCreamToucan

Reputation: 28705

leaf.names <- function(X) names(rlang::squash(X))

or

leaf.names <- function(X){
  while(any(sapply(X, is.list))) X <- purrr::flatten(X) 
  names(X)
}

gives

leaf.names(X)
# [1] "a"       "alpha.c" ""        "d"  

Upvotes: 1

Related Questions