Reputation: 3496
I have the following list:
list(list(list(name = 'John'), list(name=c("Jack", "Kate"))))
[[1]]
[[1]][[1]]
[[1]][[1]]$name
[1] "John"
[[1]][[2]]
[[1]][[2]]$name
[1] "Jack" "Kate"
and I would like to extract a list of name
only. I know I can use
list(list(list(name = 'John'), list(name=c("Jack", "Kate"))))%>% map(list(1, 'name'))
to extract name from the first element. But how do I extract name
from every element to get this:
#[[1]]
#[1] "John"
#[[2]]
#[1] "Jack" "Kate"
UPDATE: I just realized I could use flatten()
, but how would I do it using map with proper indexing?
Upvotes: 2
Views: 1465
Reputation: 8107
mylist <- list(list(list(name = 'John'), list(name=c("Jack", "Kate"))))
library(purrr)
map(mylist[[1]], ~ .[[1]]) %>%
flatten_chr()
# [1] "John" "Jack" "Kate"
I assumed that you wanted to return a vector of names, as opposed to another list.
EDIT: Never mind you wanted to keep it as a list.
Upvotes: 2
Reputation: 26343
You could use modify_depth
, pluck
, and flatten
here, all functions from purrr
your_list <- list(list(list(name = 'John'), list(name=c("Jack", "Kate"))))
library(purrr)
modify_depth(your_list, .depth = 2, .f = pluck, "name") %>%
flatten()
#[[1]]
#[1] "John"
#[[2]]
#[1] "Jack" "Kate"
Upvotes: 3