I have two datasets. The first one contains a list of cities and their distance in miles from destinations. The second list contains the destinations. I want to use purrr to put the name of the closest destination into a new column in the first dataset.
Here's the first dataset (with made up data/distances):
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))
Here's the second dataset with the destinations:
library(tidyverse)
data2 <- tibble(destination = c("Rome Italy", "Miami United States", "Singapore Singapore", "Toronto Canada"))
And here's what I want it to look like:
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"))
I'm ideally looking for a tidy solution, and I have attempted to do this with purrr but to no avail. This is my failed attempt:
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'
Thank you!