Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading