I am trying to use R with the tidyverse packages and having trouble applying a function to my data. My data includes lat/long coordinates, and I want to calculate the distance from every location (row of my data frame) to a reference location. I am trying to use the geosphere::distm function.
library(tidyverse)
library(geosphere)
my_long <- 172
my_lat <- -43
data <- data %>% rowwise() %>% mutate(
dist = distm(c(myLong, myLat), c(long, lat), fun=distHaversine) # this works
)
I got it working using the rowwise()
function, as above, but this is deprecated, so I want to know how to do it with modern tidyverse
, i.e., dplyr
or purrr
, I think, for example the closest I have got is using map2:
my_distm <- function(long1, lat1, long2, lat2)
distm(c(long1, lat1), c(long2, lat2), fun=distHaversine)
data <- data %>% mutate(
dist = map2(long, lat, my_distm, my_long, my_lat) # this doesn't
)
So far I have failed.
Vectorize(my_distm)
and it should work directly in yourmutate()
call. – Steven Beaupré