rpurrrpluck

Using map to pluck from nested list


I'm trying to familiarize myself with purrr, map and pluck and I have a deeply nested list:

test_list <- 
    list(
      outer_1 = list(
        list(
          inner_1 = list(pluck = "String I Want", dontpluck = "other string")
        )
      )
    )
$outer_1
$outer_1[[1]]
$outer_1[[1]]$inner_1
$outer_1[[1]]$inner_1$pluck
[1] "String I want"

$outer_1[[1]]$inner_1$dontpluck
[1] "other string"

And I'd like to extract "String I want"

I know I can get the string using

test_list$outer_1[[1]]$inner_1$pluck

But I'd like to abstract this using map but I'm missing some steps. (mainly I don't know how to emulate the [[1]] part using map - something like:

map(test_list, "outer_1") %>%
  map("inner_1") %>%
  map("pluck")

Desired Output

[1] "String I want"

Solution

  • One way could be:

    map_chr(pluck(test_list, "outer_1"), pluck, "inner_1", "pluck")
    
    [1] "String I Want"