Last active
February 4, 2019 18:10
-
-
Save mpettis/6f115665bdd3728977cb1baef8776d49 to your computer and use it in GitHub Desktop.
Using geosphere/haversine matrix function with dplyr mutate operations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| library(geosphere) | |
| library(tidyverse) | |
| # Simple dataframe and use case: | |
| ref_ll <- c(-95.0, 45.0) | |
| df__ <- tribble( | |
| ~lon, ~lat, | |
| -95.0, 45.0, | |
| -96.0, 45.0, | |
| -95.0, 44.0, | |
| -96.0, 44.0 | |
| ) | |
| # This will do it naturally | |
| distHaversine(ref_ll, df__ %>% as.matrix()) | |
| #> [1] 0.00 78714.27 111319.49 136731.40 | |
| # This will do the lon/lat rows against the single reference latitude/longitude: | |
| df__ %>% | |
| mutate(ttl_distance = distHaversine(ref_ll, matrix(c(lon, lat), ncol=2))) | |
| #> # A tibble: 4 x 3 | |
| #> lon lat ttl_distance | |
| #> <dbl> <dbl> <dbl> | |
| #> 1 -95 45 0 | |
| #> 2 -96 45 78714. | |
| #> 3 -95 44 111319. | |
| #> 4 -96 44 136731. | |
| # If the reference lat/lons are in the dataframe, this will do it | |
| # Not handling missing values here at all... | |
| df__ <- tribble( | |
| ~lon, ~lat, ~reflon, ~reflat, | |
| -95.0, 45.0, -95.0, 45.0, | |
| -96.0, 45.0, -95.0, 45.0, | |
| -95.0, 44.0, -97.0, 43.0, | |
| -97.0, 43.0, -97.0, 43.0, | |
| -96.0, 44.0, -97.0, 43.0, | |
| ) | |
| # Make a m x 2 matrix out of the reference lon/lat and target lon/lat, and feed those results in. | |
| # `matrix()` will create the appropriate matrix. | |
| df__ %>% | |
| mutate(ttl_distance = distHaversine(matrix(c(reflon, reflat), ncol=2), matrix(c(lon, lat), ncol=2))) | |
| #> # A tibble: 5 x 5 | |
| #> lon lat reflon reflat ttl_distance | |
| #> <dbl> <dbl> <dbl> <dbl> <dbl> | |
| #> 1 -95 45 -95 45 0 | |
| #> 2 -96 45 -95 45 78714. | |
| #> 3 -95 44 -97 43 196136. | |
| #> 4 -97 43 -97 43 0 | |
| #> 5 -96 44 -97 43 137520. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment