【问题标题】:Distance matrix geographic points (capital cities) [duplicate]距离矩阵地理点(首都)[重复]
【发布时间】:2017-05-05 18:15:55
【问题描述】:

我希望创建一个世界各国首都城市的距离矩阵。我已经创建了一个像这样的国家质心距离矩阵。 shapefile 来源于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

现在我想做同样的事情,但使用国家首都而不是国家质心。理想情况下,即使我有其他不是首都的地理点,我也想要一种有效的方法。到目前为止,我已经在给定的 shapefile 上绘制了大写字母,但我找不到一种方法来从中创建距离矩阵。

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)

理想的输出格式应该是这样的

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

其中 x 表示各个国家首都之间的距离,以米或公里为单位。

【问题讨论】:

    标签: r matrix


    【解决方案1】:

    我认为您所需要的只是一个计算纬度/经度给定点之间距离的函数。这在 geosphere 包中可用。

    library(geosphere)
    Caps = cbind(world.cities$long, world.cities$lat)
    CapDistMatrix = distGeo(Caps, Caps)
    

    【讨论】:

    • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您正在为将来的读者回答问题,而这些人可能不知道您的代码建议的原因。也请尽量不要用解释性的 cmets 挤满你的代码,这会降低代码和解释的可读性!
    • 我这样做了,但最后使用了 distm。这似乎是正确的,所以我会坚持下去。感谢您的帮助!
    猜你喜欢
    • 2018-02-10
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2016-12-06
    • 2011-08-08
    相关资源
    最近更新 更多