Programming
r nested-lists names
Updated Sat, 16 Jul 2022 14:33:28 GMT

Extract names of second [given] level of nested list in R


I have a nested list. Each level of this list is named (as in provided dummy example). I want to extract the names (unique) from the 2nd level of my initial list, so I will be able to use them in some further operations.

I know how to do it in two steps, but I wonder whether there is more efficient/elegant solution. Also I wonder whether the regex approach would be faster (I am noob at regex).

Here is a dummy list:

x <- list(one = list(one_1 = list(seq = 1:9, start = 1, end = 5), 
one_2 = list(seq = 2:11, start = 2, end = 6), one_3 = list(
    seq = 3:12, start = 3, end = 7)), two = list(two_1 = list(
seq = 1:13, start = 8, end = 222), two_2 = list(seq = 1:14, 
start = 13, end = 54)))

And here is my code:

allnames <- names(rapply(x, function(x) head(x, 1)))
desirednames <- unique(sapply(strsplit(allnames, ".", fixed=TRUE), "[", 2))



Solution

A possible solution, based on purrr::map_depth:

library(tidyverse)
map_depth(x, 1, names) %>% unlist(use.names = F)
#> [1] "one_1" "one_2" "one_3" "two_1" "two_2"




Comments (1)