Not for the first time, I'm trying to solve the following problem.
I am trying to loop over rows of a data frame and put the result back into the said data frame. The result for each row is more than 1 new rows, and I'm tripping up on it.
For each city in a data frame, I want to get a list of nearest stations. I'd like to have a row per each city-station pair, or at least have a nested data frame (which I'd later unnest
and get the desired pairs anyway).
The output of GSODR::nearest_stations
is a vector, and I can't bend it to appear row-wise. Please send help.
Here is a reprex
:
library(tidyverse)
library(maps)
library(GSODR)
# Get a sample of cities
cities <- maps::world.cities %>%
filter(country.etc == 'USA') %>%
arrange(desc(pop)) %>%
select(name, lat, long) %>%
head(10)
# Get nearest stations for each city.
# This works, but stations are one long vector per city.
# Expected output for the function, but not what I want
stations_c <- cities %>%
mutate(stations = purrr::map2(lat, long, nearest_stations, distance = 10))
# This method doesn't work.
stations_rows <- cities %>%
mutate(stations = purrr::map2_dfr(lat, long, nearest_stations, distance = 10))
#> Error in mutate_impl(.data, dots): Evaluation error: Argument 1 must have names.
Created on 2019-03-25 by the reprex package (v0.2.1)
The Evaluation error: Argument 1 must have names.
is really a bind_rows()
error, but I can't figure out how to fix it.