lethalSinger
lethalSinger

Reputation: 616

using purrr to extract elements from multiple lists starting with a common letter

I have a list of lists. One element in each list has a name beginning with "n_". How do I extract these elements and store them in a separate list? Can I use a combination of map and starts_with?

E.g.:

m1 <- list(n_age = c(19,40,39),
       names = c("a", "b", "c"))

m2 <- list(n_gender = c("m","f","f"),
       names = c("f", "t", "d"))

nice_list <- list(m1, m2)

I was hoping that something like the following to work (it doesn't!):

output <- map(nice_list, starts_with("n_"))

Upvotes: 3

Views: 610

Answers (2)

Aur&#232;le
Aur&#232;le

Reputation: 12819

You could (ab)use partial matching of $:

map(nice_list, `$`, "n_")

(I don't really recommend it).

(And I can't figure out why lapply(nice_list, `$`, "n_") doesn't work (gives a list(NULL, NULL)).

Upvotes: 2

Maurits Evers
Maurits Evers

Reputation: 50668

How about this?

map(nice_list, ~.x[grep("n_", names(.x))])
#[[1]]
#[[1]]$n_age
#[1] 19 40 39
#
#
#[[2]]
#[[2]]$n_gender
#[1] "m" "f" "f"

Or using starts_with

map(nice_list, ~.x[starts_with("n_", vars = names(.x))])

Or to flatten the nested list, you could do

unlist(map(nice_list, ~.x[grep("n_", names(.x))]), recursive = F)
#$n_age
#[1] 19 40 39
#    
#$n_gender
#[1] "m" "f" "f"

Upvotes: 1

Related Questions