繁体   English   中英

使用 purrr::map 迭代多个列表

[英]Iterating over multiple lists using purrr::map

下面是我的数据

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))

数据是来自 R 库“gapminder”的 gapminder 数据。

我想使用 purrr 找到每个大陆每年 gdpPercap 最高的国家/地区。

但是,这段代码给了我一个错误,即我的两个列表的长度不同 当长度不同时,迭代两个列表的映射语法是什么? 我应该如何使用它来修复代码并实现我的目标?

我会通过分组和嵌套来做到这一点:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM