Dambo
Dambo

Reputation: 3496

How to subset a list using map?

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

Answers (2)

Phil
Phil

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

markus
markus

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

Related Questions