rpurrrpluck

Using map and pluck to get values from nested list


I have the following nasty, nested list

Edit: updated to include value_I_dont_want

mylist <- list(
  list(
    nested_1 = list(
      nested_2 = list(
        list( value_I_want = "a", value_I_dont_want = "f"),
        list( value_I_want = "b", value_I_dont_want = "g")
      )
    )
  ),
  list(
    nested_1 = list(
      nested_2 = list(
        list( value_I_want = "c", value_I_dont_want = "h"),
        list( value_I_want = "d", value_I_dont_want = "i"),
        list( value_I_want = "e", value_I_dont_want = "j")
      )
    )
  )
)

And I want to get all the value_I_wants

I know I can use the following code within a for loop

mylist[[x]]$nested_1$nested_2[[y]]$value_I_want

But I want to improve my map skills. I understand how to use map_chr when the list is a single level but I haven't found many resources on plucking from very nested lists. I also know I can use [[ but haven't found good documentation for when this is appropriate?

Any help appreciated!


Solution

  • If we need the 'yay's

    library(purrr)
    library(dplyr)
    map(mylist, ~ .x$nested_1$nested_2 %>% unlist%>% grep("^yay", ., value = TRUE))
    

    Or use pluck to extract the elements based on the key 'value_I_want' after looping over the list with map

    map(mylist, ~ .x$nested_1$nested_2 %>% 
                         map(pluck, "value_I_want") )