繁体   English   中英

R 如何计算具有经度和纬度的几个点之间的距离(以公里为单位)

[英]R how to calculate the distance in km between several points that have long and lat

我有三个点,经度和纬度(三个岛,见下面的矩阵),我想计算它们之间的距离(以公里为单位)。 这是我的矩阵(list1):

list1 <- data.frame(longitude = c(-3.0000,
                                   -1.3333,
                                   -6.5667), 
                     latitude = c(59.0000, 
                                  60.3333,  
                                  62.2500),
                      name= c('Orkney', 
                            'Shetlands', 
                               'Faroe'))

我只想知道法罗群岛和设得兰群岛之间的距离,设得兰群岛和奥克尼群岛之间的距离等等......我是R的初学者所以我对语言不熟悉......可以谁来帮帮我?

您正在寻找的是距离矩阵。 可以用geodist package 来完成

library(geodist)

distance_matrix <- geodist(list1, measure = 'geodesic' )/1000 #converting it to km

#also, check for other measures in the description

colnames(distance_matrix) <- list1$name
rownames(distance_matrix) <- list1$name

Output:

            Orkney Shetlands    Faroe
Orkney      0.0000  175.7363 411.2688
Shetlands 175.7363    0.0000 352.4388
Faroe     411.2688  352.4388   0.0000

这是两种可能的解决方案:

list1 <- data.frame(longitude = c(-3.0000,
                                  -1.3333,
                                  -6.5667), 
                    latitude = c(59.0000, 
                                 60.3333,  
                                 62.2500),
                    name= c('Orkney', 
                            'Shetlands', 
                            'Faroe'))
require(sf)
#> Loading required package: sf
#> Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1
st_distance(st_as_sf(list1, coords = 1:2, crs=4326))
#> Units: [m]
#>          [,1]     [,2]     [,3]
#> [1,]      0.0 175316.8 410279.5
#> [2,] 175316.8      0.0 351338.2
#> [3,] 410279.5 351338.2      0.0
require(geosphere)
#> Loading required package: geosphere
do.call(rbind,lapply(split(list1[,1:2],1:3), distHaversine, p2=list1[,1:2]))
#>       [,1]     [,2]     [,3]
#> 1      0.0 175512.9 410738.5
#> 2 175512.9      0.0 351731.2
#> 3 410738.5 351731.2      0.0

reprex package (v2.0.1) 创建于 2021-09-30

这里coords=1:2表示包含经度和纬度的列,这也可以通过名称完成更多详细信息,请参阅?st_as_sfcrs=4326代表使用的坐标参考系统(epsg 代码: https://epsg.io/ 4326 )。 st_distance自动附加单位。 如果您想要不同的单位,单位 package 有如何转换为不同单位的示例。

第二个例子稍微没那么花哨,只适用于长纬度数据,因为它使用distHaversine (geosphere 包含替代距离函数)。 lapply用于每次计算一个坐标和所有其他坐标之间的距离。

rownamescolnames可用于再次附加名称。 坐标保持相同的顺序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM