r - purrr 找到最小值,然后用 case_when 标记

标签 r string dplyr purrr pmap

我有两个数据集。第一个包含城市列表及其与目的地的距离(以英里为单位)。第二个列表包含目的地。我想使用 purrr 将最近目的地的名称放入第一个数据集中的新列中。

这是第一个数据集(包含合成数据/距离):

library(tidyverse)
data1 <- tibble(city = c("Atlanta", "Tokyo", "Paris"),
                   dist_Rome = c(1000, 2000, 300),
                   dist_Miami = c(400, 3000, 1500),
                   dist_Singapore = c(3000, 600, 2000),
                   dist_Toronto = c(900, 3200, 1900))

这是带有目的地的第二个数据集:

library(tidyverse)
data2 <- tibble(destination = c("Rome Italy", "Miami United States", "Singapore Singapore", "Toronto Canada"))

这是我想要的样子:

library(tidyverse)
solution <- tibble(city = c("Atlanta", "Tokyo", "Paris"),
                   dist_Rome = c(1000, 2000, 300),
                   dist_Miami = c(400, 3000, 1500),
                   dist_Singapore = c(3000, 600, 2000),
                   dist_Toronto = c(900, 3200, 1900),
                   nearest = c("Miami United States", "Singapore Singapore", "Rome Italy"))

理想情况下,我正在寻找一个整洁的解决方案,并且我已经尝试使用 purrr 来做到这一点,但无济于事。这是我失败的尝试:

library(tidyverse)
solution <- data1 %>%
  mutate(nearest_hub = map(select(., contains("dist")), ~
                                  case_when(which.min(c(...)) ~ data2$destination),
                                TRUE ~ "NA"))
Error in which.min(c(...)) : 
  (list) object cannot be coerced to type 'double'

谢谢!

最佳答案

我们可以收集成'long'格式,按'city'分组,切片具有最小'val'的行,left_join用'data2'得到'最近的'

library(tidyverse)
data1 %>% 
   gather(key, val, starts_with("dist")) %>% 
   group_by(city) %>% 
   slice(which.min(val)) %>% 
   ungroup %>%
   transmute(city, key = str_remove(key, 'dist_')) %>% 
   left_join(data2 %>% 
   mutate(key = word(destination, 1))) %>%
   select(city, nearest = destination) %>% 
   left_join(data1)

关于r - purrr 找到最小值,然后用 case_when 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56657395/

相关文章:

r - 如何在一张覆盖有透明度的条形图上绘制两个字符变量的频率

c - 在 C 中屏蔽打印的字符串

R glm - 如何进行多重交叉验证

Java将读取的行分割成字符串然后使用它们

c++ - 在项目之间共享源文件

r - Purrr 和映射向量输出函数

r - r 中比 sqldf 更快的任何其他进程

r - R 中的过滤/子集应用于多列

r - 在 if 语句中比较两个向量

macos - 创建 R 包时,错误 ['\+' 是从 "\+"开始的字符串中无法识别的转义