2

I do have the following simple example of a nested list:

list(list(structure(list(group = "a", def = "control"), .Names =  c("group", 
"def"))), list(structure(list(group = "b", def = "disease1"), .Names = c("group", 
"def"))))

The structure is as follows:

str(t1)
List of 2
$ :List of 1
..$ :List of 2
.. ..$ group: chr "a"
.. ..$ def  : chr "control"
$ :List of 1
..$ :List of 2
.. ..$ group: chr "b"
.. ..$ def  : chr "disease1"

Is there an easy way of getting only the nested list that satisfies a specific condition. As an example, if I knew only the name of the group, e.g., "a", how would I get the according sublist; in the example, this would be the first nested list:

[[1]]
[[1]]$group
[1] "a"

[[1]]$def
[1] "control"

So essentially I am looking for a way to apply group == "a" in this nested list structure.

Oliver
  • 441
  • 6
  • 14

3 Answers3

2

We can extract a sublist of a list using lapply. We can write a function as well.

get_sublist <- function(group_name) {
   lst[lapply(lst, function(x) x[[1]][[1]]) == group_name]
}


get_sublist("a")
#[[1]]
#[[1]][[1]]
#[[1]][[1]]$group
#[1] "a"

#[[1]][[1]]$def
#[1] "control"

get_sublist("b")
#[[1]]
#[[1]][[1]]
#[[1]][[1]]$group
#[1] "b"

#[[1]][[1]]$def
#[1] "disease1"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

We can convert to tibble and then with map create a logical vector to subset the 'lst'

library(purrr)
library(magrittr)
library(tibble)
lst %>% 
      map_lgl(., ~map_lgl(., ~as.tibble(.) %>%
      .$group=='a')) %>%
       extract(lst, .) %>%
       .[[1]]
#[[1]]
#[[1]]$group
#[1] "a"

#[[1]]$def
#[1] "control"

Or use the modify_depth

lst %>% 
     modify_depth(., 2, ~as.tibble(.)[['group']]=='a') %>%
     unlist %>%
     extract(lst, .)

Here, we assume that the position of 'group' can change in the list.

akrun
  • 874,273
  • 37
  • 540
  • 662
0

On top of the answers already provided, I have also managed to get the correct results using "keep" from the "purrr" library:

library(purrr)
get_sublist <- function(group_name) {
keep(l, function(x) x[[1]][[1]] == group_name)
}
get_sublist("b")
Oliver
  • 441
  • 6
  • 14