数据框中每个参与者之间的地理空间距离矩阵?

问题描述

晚上好, 我正在尝试计算从数据框中的每一行到其他行的距离。我的数据如下所示:

gps <- data.frame(company = c("Jonas","Felix","Maria","Anna"),longitude = c(42.33606636507468,37.66663067079797,35.68203407502485,49.424044748467686),latitude = c(-87.83678044061604,-122.39787657270155,139.6860258167475,8.674680432095006))

输出应该类似于一个 4*4 矩阵,列出每个人之间的距离,就像这样(当然,这些数字是组成的):

result <- matrix(1:12,nrow = 4,ncol = 4)
result <- cbind(c(0,1,5,6),c(1,3,7),c(5,c(6,7,0))

到目前为止,我已经尝试使用 geosphere 包:

gps_mat <- distm(gps[,c('longitude','latitude')],gps[,fun=distvincentyEllipsoid)

但是,我收到错误“.pointsToMatrix(x) 中的错误:纬度

任何帮助将不胜感激。

解决方法

我找到了 sf-package 并认为这有效:

library(sf)

gps_sf <- st_as_sf(gps,agr = NA_agr_,coords = c("longitude","latitude"),remove = TRUE,na.fail = TRUE,sf_column_name = NULL
)

gps_matrix <- st_distance(gps_sf)

如果有更优雅的方式或对我的 geosphere-approach 产生的错误的解释,我很想听听。