简体   繁体   中英

Accessing multiple levels of a deeply nested lists when a level has no name

I just can't seem to figure out how to access multiple elements of a list when one of the elements is nested at a different level and doesn't have a name. In the example below I can extract the title element easily enough:

library(purrr)

obj1 <- list(resource = list(list(format = "a"), list(format = "b")), title = "blue")
obj2 <- list(resource = list(list(format = "y"), list(format = "z")), title = "red")

x <- list(foo = obj1, bar = obj2)

imap(x[1:length(x)], ~ {
  paste0(.y, ": ", .x[["title"]])
})
#> $foo
#> [1] "foo: blue"
#> 
#> $bar
#> [1] "bar: red"

Created on 2019-02-07 by the reprex package (v0.2.1)

My goal though is to have an output which accesses these elements:

x[["foo"]][["resource"]][[1]][["format"]]
x[["foo"]][["resource"]][[2]][["format"]]
x[["bar"]][["resource"]][[1]][["format"]]
x[["bar"]][["resource"]][[2]][["format"]]

And then ultimately the output looks something like this:

#> $foo
#> [1] "foo: blue (a,b)"
#> 
#> $bar
#> [1] "bar: red (y,z)"

It seems like I should be able to do this within one purrr statement but I can't quite figure it out.

Using purrr , we can also use pluck() and map to get values from the list. This seems to return what you want

imap(x, ~paste0(
    .y, ": ", pluck(.x, "title"),
    " (", 
    paste0(map_chr(pluck(.x, "resource"), pluck, "format"), collapse=","), 
    ")"))

This returns

$foo
[1] "foo: blue (a,b)"
$bar
[1] "bar: red (y,z)"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM