如何解决计算2个坐标之间的距离函数

问题描述 投票:0回答:1

我现在有坐标(CHR)和经度纬度和(NUM)的列。我想创建一个功能,可以找到每两个坐标之间的距离。像第一和第二坐标,第二和第三,一个等之间的距离。我曾经尝试都的方式去创造。

data$new.Distance[2:n] <- distm(data$Coord[1:(n-1)], data$Coord[2:n], fun = distMeeus)
data$new.Distance[2:n] <- distm(
    c(data$longitude[1:(n-1)], data$latitude[1:(n-1)]), 
    c(data$longitude[2:n], data$latitude[2:n]), 
    fun = distMeeus
)

我得到错误信息:

ERROR in N-1: non-numeric argument to binary operator. 

我应该如何解决呢?或者是有任何其他方式R中创建这个?谢谢。

r geosphere
1个回答
0
投票

如果你问一个问题,请包括示例数据。

p <- rbind(c(0,0),c(90,90),c(10,10),c(-120,-45))
colnames(p) <- c("lon", "lat")
p
#      lon lat
#[1,]    0   0
#[2,]   90  90
#[3,]   10  10
#[4,] -120 -45

为了从第一距离到第二点,第二至第三点,依此类推,你可以做

library(geosphere)
distGeo(p)    
#[1] 10001966  8896111 13879039

要么

distMeeus(p)    
#[1] 10001959  8896115 13879009

为了让所有(LON / LAT)指向所有点的距离,你可以使用geosphere::distm;提供选择的距离函数(distGeo是默认的和最精确的)。

library(geosphere)
distm(p, fun=distGeo)
#         [,1]     [,2]     [,3]     [,4]
#[1,]        0 10001966  1565109 12317881
#[2,] 10001966        0  8896111 14986910
#[3,]  1565109  8896111        0 13879039
#[4,] 12317881 14986910 13879039        0

您还可以使用raster::pointDistance

library(raster)
d <- pointDistance(p, lonlat=TRUE)

as.dist(d)
#         1        2        3
#2 10001966                  
#3  1565109  8896111         
#4 12317881 14986910 13879039

也可以让两组点之间的距离,可能与不同数量的点。例如:

pointDistance(p, p[1:2,], lonlat=TRUE)
#         [,1]     [,2]
#[1,]        0 10001966
#[2,] 10001966        0
#[3,]  1565109  8896111
#[4,] 12317881 14986910
© www.soinside.com 2019 - 2024. All rights reserved.