在R中,如何确定我的x,y数据框中哪两行具有最小距离?

问题描述

在R中,我有一个x,y为经纬度的数据帧。如何找到最短距离的行并在新列中分配一个数字来显示此行?下面的一个简单示例显示了(5,3)和(5,2)两行,它们之间的距离最小,并且C列为它们提供了相同的数字分组。

df

解决方法

我想您可能需要distm软件包中的library(geosphere)

library(geosphere)
xy <- setNames(data.frame(rbind(c(0,0),c(90,90),c(10,10),c(-120,-45))),c("lon","lat"))
d <- distm(xy)
inds <- which(min(d[d>0])==d,arr.ind = TRUE)
out <- cbind(xy,C = NA)
out$C[inds[,"row"]] <- 1

给出

> out
   lon lat  C
1    0   0  1
2   90  90 NA
3   10  10  1
4 -120 -45 NA

虚拟数据

> dput(xy)
structure(list(lon = c(0,90,10,-120),lat = c(0,-45
)),class = "data.frame",row.names = c(NA,-4L))