Using map function to filter a data.frame element with list names

Viewed 256

This is my list

mylist <- list(setosa = iris,versicolor = iris, virginica = iris)

I have to use filter dplyr function. But the argument should be the name of the list element that map is interate, because my list is much more bigger:

map(mylist, ~ .x %>% filter(Species == 'name_of_(.x)_element_list')

I tried to do something like this, but didnt work:

map(mylist, ~ .x %>% filter(Species == {{names(.x)}})

Any help

3 Answers

You could try this:

map2(mylist, names(mylist), \(l, n) filter(l, Species == n))

Edit: Or with a purrr-style lambda function:

map2(mylist, names(mylist), ~ filter(.x, Species == .y))

I think we can also use imap function here, but I hope I got what you have in mind correctly. It is very similar to map2 just as .x is iterating on the values and .y is iterating on the names (positions):

library(purrr)

mylist %>%
  imap(~ .x %>% filter(Species == .y))

Using base R

Map(function(x, y) subset(x, Species == y),mylist, names(mylist))
Related