Using the geosphere distm function on a data.table to calculate distances

前端 未结 1 891
孤城傲影
孤城傲影 2020-12-11 17:10

I\'ve created a data.table in that has 6 columns. My data.table has a columns compairing two locations: Location 1 and Location 2. I\'m trying to use the distm function to

相关标签:
1条回答
  • 2020-12-11 18:03

    The distm fucntion generates a Distance matrix of a set of points. Are you sure this is the function you want if you're just comparing the points on each row, and adding one column?

    It sounds like you actually want either distHaversine or distGeo

    library(data.table)
    library(geosphere)
    
    dt <- read.table(text = "LOC_1_ID LOC1_LAT_CORD LOC1_LONG_CORD LOC_2_ID LOC2_LAT_CORD LOC2_LONG_CORD
    1       35.68440        -80.48090        70624    34.86752   -82.46632
    6       35.49770        -80.62870        70624    34.86752   -82.46632
    10       35.66042        -80.50053        70624    34.86752   -82.46632", header = T)
    
    setDT(dt)
    dt[, distance_hav := distHaversine(matrix(c(LOC1_LONG_CORD, LOC1_LAT_CORD), ncol = 2),
                                       matrix(c(LOC2_LONG_CORD, LOC2_LAT_CORD), ncol = 2))]
    
    #     LOC_1_ID LOC1_LAT_CORD LOC1_LONG_CORD LOC_2_ID LOC2_LAT_CORD LOC2_LONG_CORD distance_hav
    # 1:        1      35.68440      -80.48090    70624      34.86752      -82.46632     202046.3
    # 2:        6      35.49770      -80.62870    70624      34.86752      -82.46632     181310.0
    # 3:       10      35.66042      -80.50053    70624      34.86752      -82.46632     199282.1
    

    Update: This answer gives a more efficient version of distHaversine for use in data.table

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