簡體   English   中英

計算兩點之間的距離,但僅針對成對的子集

[英]Calculating distance between two points, but only for a subset of pairs

我正在嘗試計算坐標對之間的距離,使用(例如)rgeos包中的gDistance函數相當容易。 但是,我在解決以下問題時遇到了問題:在我的數據框中,我掌握了有關不同類型興趣點的信息(比如說咖啡店,快餐店和酒吧),而我只對兩個POI之間的距離感興趣不同的類型。

這是我的數據框的樣子:

    lat <- c(50.639342, 50.623727, 50.578924, 50.786729)
    lon <- c(10.236543, 10.1896532, 10.587272, 10.776234)
    type <- c("A", "A", "B", "C")
    df <- data.frame(lat, lon, type)

我可以通過將df轉換為空間對象來計算每對之間的距離...

    if (!require(sp)) install.packages('sp')
    library(sp)
    sp.data <- df
    coordinates(sp.data) <- ~lat+lon

...並使用gDistance函數獲得距離的成對矩陣。

    if (!require(rgeos)) install.packages('rgeos')
    library(rgeos)
    distance <- gDistance(sp.data, byid=T)
    distance
    1          2         3         4
    1 0.00000000 0.04942147 0.3558949 0.5594545
    2 0.04942147 0.00000000 0.4001350 0.6088076
    3 0.35589488 0.40013500 0.0000000 0.2808728
    4 0.55945447 0.60880759 0.2808728 0.0000000

接下來,我只想分析不同類型的兩點之間的距離。 例如,我對最接近咖啡店而不是咖啡店的鄰居感興趣。 我的問題是我不知道如何使用成對數據。 理想情況下,我將使用原始數據幀中的type列將NA分配給包含相同類型點之間距離的所有像元,但我不知道該怎么做。

您可以使用?outer ,請嘗試以下操作:

lat <- c(50.639342, 50.623727, 50.578924, 50.786729)
lon <- c(10.236543, 10.1896532, 10.587272, 10.776234)
type <- c("A", "A", "B", "C")
df <- data.frame(lat, lon, type)
library(sp)
sp.data <- df
coordinates(sp.data) <- ~lat+lon
library(rgeos)
distance <- gDistance(sp.data, byid=T)
distance
sp.data$type # we will use columns from the original data frame as you want

# solution
colnames(distance) <- sp.data$type
rownames(distance) <- sp.data$type
distance[outer(rownames(distance), colnames(distance), "==")] <- NA
distance

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM