Search code examples
rdplyrplyrpurrrmagrittr

Iterating over multiple lists using purrr::map


Below is my data

library(gapminder)
library(tidyverse)
lst <- unique(gapminder$continent)
ylst = c(2007, 1952)
map2_dfr(lst,ylst, ~gapminder %>% filter(continent == .x & year == .y) %>% 
          arrange(desc(gdpPercap))
        %>% slice(1) %>% select(continent, country,gdpPercap,year))

The data is the gapminder data from the R library 'gapminder'.

I want to find the country with the highest gdpPercap for each year for each continent using purrr.

However this code is giving me the error that the lengths of my two lists are not the same What is the map syntax to iterate over two lists, when the lengths are not the same? And how should I use that to fix the code and achieve my objective?


Solution

  • I would do this by grouping and nesting:

    gapminder %>% 
      filter(year %in% ylst) %>% 
      group_by(continent, year) %>% 
      nest() %>% 
      mutate(data=map(data, ~top_n(., 1, gdpPercap))) %>% 
      unnest(c(data)) %>% 
      select(continent, country,gdpPercap,year)