Geosphere/dplyr:创建坐标之间的距离矩阵 [英] Geosphere/dplyr: create matrix of distance between coordinates

查看:75
本文介绍了Geosphere/dplyr:创建坐标之间的距离矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建多个坐标之间的距离的矩阵".最好使用dplyr/geosphere.我已经看到geosphere软件包提供了此功能.我设法创建了两个向量之间的距离,但是在创建完整矩阵时遇到了困难.

I want to create a "matrix" of the distance between multiple coordinates with each other. Preferably using dplyr/geosphere. I already saw that the geosphere package offers this. I managed to create the distance between two vectors but I have difficulties creating the full matrix.

这是具有多个坐标的示例表.

This is the sample table with multiple coordinates.

df <- data.frame(latitude = c(49.48609,-8.14671,11.28625),
                 longitude = c(8.463678,143.05793,-11.18285))

  latitude  longitude
1 49.48609   8.463678
2 -8.14671 143.057930
3 11.28625 -11.182850

这是我正在寻找的输出:

And this is the output I am looking for:

  latitude    longitude    distance-latlon1    distance-latlon2   distance-latlon3                 
1 49.48609     8.463678    NA                  *latlon2><latlon1  *latlon3><latlon1
2 -8.14671   143.057930    *latlon1><latlon2   NA                 *latlon3><latlon2
3 11.28625   -11.182850    *latlon1><latlon3   *latlon2><latlon3  NA

我尝试使用geosphere,但只找到一种方法来计算两列之间的距离(在此代码段中为0).

I tried out using geosphere but I only found a way to calculate the distance between two columns (which in this snippet results in a 0).

library(geosphere) 
df$distance <- distVincentyEllipsoid(df[,c('longitude','latitude')],
                                     df[,c('longitude','latitude')])

推荐答案

您需要 geosphere -package的 distm 功能.使用:

You need the distm function of the geosphere-package. With:

# create a distance matrix
m <- distm(df[2:1], df[2:1], fun = distVincentyEllipsoid)

# replace the diagonal with NA
diag(m) <- NA

# make column names for the distance matrix
colnames(m) <- paste0('r',1:nrow(df))

# bind the distance matrix to the dataframe
cbind.data.frame(df, m)

您得到:

  latitude  longitude       r1       r2       r3
1 49.48609   8.463678       NA 13792423  4606658
2 -8.14671 143.057930 13792423       NA 17189185
3 11.28625 -11.182850  4606658 17189185       NA

这篇关于Geosphere/dplyr:创建坐标之间的距离矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆