Calculating great-circle distance matrix

前端 未结 1 876
攒了一身酷
攒了一身酷 2021-01-15 05:27

dist(coords) provides the distance matrix using Euclidean distances; it also provides several other options. But it doesn\'t provide any option such as the have

相关标签:
1条回答
  • 2021-01-15 06:07

    As you may already have noticed, distHaversine() will compute the distance between a single point and a two-column matrix of coordinates.

    To compute all pairwise distances between two coordinate matrices, just use apply() to iterate row-by-row through one of the matrices, computing each of its points' distance to all of the points in the other.

    library(geosphere)
    
    ## Example coordinates (here stored in two column matrices)
    cc1 <- rbind(c(0,0),c(1,1))
    cc2 <- rbind(c(90,0),c(90,90), c(45,45))
    
    ## Compute matrix of distances between points in two sets of coordinates
    apply(cc1, 1, FUN=function(X) distHaversine(X, cc2))
    #          [,1]    [,2]
    # [1,] 10018754 9907452
    # [2,] 10018754 9907435
    # [3,]  6679169 6524042
    

    Interesting note: A quick glance under the hood at sp::spDists() (which does compute pairwise distances between two matrices) reveals that it uses an essentially identical apply()-based strategy. The main difference, beyond some additional error checking and argument passing is that it applies the function spDistsN1() where we apply distHaversine().

    0 讨论(0)
提交回复
热议问题