0

I'm looking to create a distance matrix of the capital cities of countries around the world. I have created a distance matrix of country centroids like this. Shapefile is derived from http://www.gadm.org/version2:

library(rgeos)
library(rgdal)
shapefile <- readOGR("./Map/World Map", layer = "TM_WORLD_BORDERS-0.3")

centroids <- gCentroid(shapefile, byid = TRUE, as.character(shapefile@data$UN)
dist_matrix <- as.data.frame(geosphere::distm(centroids)
colnames(dist_matrix) <- shapefile@data$NAME
rownames(dist_matrix) <- shapefile@data$NAME

Now I want to do the same thing but with country capitals instead of country centroids. Ideally I want a method that works even if I have other geographic points that aren't capitals. So far I have made it to plotting the capitals on the given shapefile but I can't find a way to create a distance matrix out of them.

library(rgeos)
library(rgdal)
library(maps)
library(tidyverse)
shapefile <- readOGR("./Map/World Map", layer = "TM_WORLD_BORDERS-0.3")

data("world.cities)
world..cities <- world.cities %>%
filter(world.cities$capital == 1)
plot(shapefile)
points(world.cities$long, world.cities$lat, col ="red", cex = .6, pch = 22, add = TRUE)

The ideal output format would look something like this

         Algeria  Albania  Azerbaijan
Algeria     0        x          x
Albania     x        0          x
Azerbaijan  x        x          0

Where x denotes the distance between the capitals of the respective countries in metres or kilometres.

vio
  • 137
  • 1
  • 10

1 Answers1

1

I think that all you need is a function that computes the distance between points given in lat/lon. That is available in the geosphere package.

library(geosphere)
Caps = cbind(world.cities$long, world.cities$lat)
CapDistMatrix = distGeo(Caps, Caps)
G5W
  • 36,531
  • 10
  • 47
  • 80
  • While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations! – kayess Dec 20 '16 at 14:48
  • I did this but used distm in the end. It appears to be correct so I'll stick with that. Thank you for your help! – vio Dec 21 '16 at 13:01