Problem
I would suppose that this should be a common problem, yet I couldn't find a solution for it:
Let's assume a deeply nested list, such as:
my_list <- list(
"first_node" = list(
"group_a" = list(
"E001" = 1:5,
"E002" = list(
"F001" = 6:10,
"F002" = 11:15
)
),
"group_b" = list(
"XY01" = list(
"Z1" = LETTERS[1:5],
"Z2" = LETTERS[6:10],
"Z3" = list(
"ZZ1" = LETTERS[1],
"ZZ2" = LETTERS[2],
"ZZ3" = LETTERS[3]
)
),
"YZ" = LETTERS[11:15]
),
"group_c" = list(
"QQQQ" = list(
"RRRR" = 200:300
)
)
),
"second_node" = list(
"group_d" = list(
"L1" = 99:101,
"L2" = 12
)
)
)
Desired Output
I want to retrieve elements by their name, that might be located at an unknown level of depth in that list. Importantly, I only want that specific element and it's children, not the parents.
For example, searching my_list for "XY01" should yield:
XY01 = list(
"Z1" = LETTERS[1:5],
"Z2" = LETTERS[6:10],
"Z3" = list(
"ZZ1" = LETTERS[1],
"ZZ2" = LETTERS[2],
"ZZ3" = LETTERS[3]
)
)
> str(XY01)
List of 3
$ Z1: chr [1:5] "A" "B" "C" "D" ...
$ Z2: chr [1:5] "F" "G" "H" "I" ...
$ Z3:List of 3
..$ ZZ1: chr "A"
..$ ZZ2: chr "B"
..$ ZZ3: chr "C"
Previous attempts
Initially I want to use rapply() to do the job, but it seems that I wouldn't be able to access names() for the current iteration. My second attempt was writing a custom recursive function:
recursive_extract <- function(haystack, needle){
lapply(names(haystack), function(x){
if (needle %in% names(haystack[[x]])) {
return(haystack[[needle]])
} else {
recursive_extract(haystack[[x]], needle)
}
}) %>% setNames(names(haystack))
}
...which also seems problematic, since lapply() will always give back the same object, even if NULL is returned, so the parental structure follows along.
I've been looking into the purrr and rlist-packages for a convenient function, but it seems that most of them don't support recursion (?).
Bonus Challenge
After extracting the desired element, I would ideally want to choose how many child-levels to return. For instance:
desired_func(haystack, needle, get_depth = 1) for the previous example would result in:
XY01 = list(
"Z1" = LETTERS[1:5],
"Z2" = LETTERS[6:10]
)
> str(XY01)
List of 2
$ Z1: chr [1:5] "A" "B" "C" "D" ...
$ Z2: chr [1:5] "F" "G" "H" "I" ...
Very grateful for help! :)