Computing Haversine Great Circle Distance in R (Example Code)
In this article you’ll learn how to compute the Haversine great circle distance in R.
Example Data
mat_ll <- matrix(c(75.13135, 79.06473, # Define longitude & latitude points 15.28734, 14.29367), ncol = 2) colnames(mat_ll) <- c("long", "lati") rownames(mat_ll) <- c("p1", "p2") mat_ll # Show longitude/latitude matrix in RStudio console # long lati # p1 75.13135 15.28734 # p2 79.06473 14.29367 |
mat_ll <- matrix(c(75.13135, 79.06473, # Define longitude & latitude points 15.28734, 14.29367), ncol = 2) colnames(mat_ll) <- c("long", "lati") rownames(mat_ll) <- c("p1", "p2") mat_ll # Show longitude/latitude matrix in RStudio console # long lati # p1 75.13135 15.28734 # p2 79.06473 14.29367
Example: Create Haversine Distance Matrix of a Set of Geographical Points
install.packages("geosphere") # Install & load geosphere library("geosphere") |
install.packages("geosphere") # Install & load geosphere library("geosphere")
distm(mat_ll, fun = distHaversine) # Return geospatial distance # [,1] [,2] # [1,] 0.0 437554.5 # [2,] 437554.5 0.0 |
distm(mat_ll, fun = distHaversine) # Return geospatial distance # [,1] [,2] # [1,] 0.0 437554.5 # [2,] 437554.5 0.0