简体   繁体   English

计算两点之间的距离,但仅针对成对的子集

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

I am trying to calculate distances between pairs of coordinates, which is fairly easy using (for example) the gDistance function in the rgeos package. 我正在尝试计算坐标对之间的距离,使用(例如)rgeos包中的gDistance函数相当容易。 I have problems figuring out the following twist, however: In my data frame, I have information on points of interest of different types (let's say coffee shops, fast food restaurants, and bars) and I am only interested in the distances between two POIs of different types. 但是,我在解决以下问题时遇到了问题:在我的数据框中,我掌握了有关不同类型兴趣点的信息(比如说咖啡店,快餐店和酒吧),而我只对两个POI之间的距离感兴趣不同的类型。

This is what my data frame looks like: 这是我的数据框的样子:

    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)

I can calculate the distances between each pair by converting the df into a spatial object... 我可以通过将df转换为空间对象来计算每对之间的距离...

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

...and using the gDistance function to obtain a pair wise matrix of distances. ...并使用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

What I would like to do next is analyze the distances between two points of different types only. 接下来,我只想分析不同类型的两点之间的距离。 For example, I am interested in what is the closest neighbor to a coffee shop that is not itself a coffee shop. 例如,我对最接近咖啡店而不是咖啡店的邻居感兴趣。 My problem is that I don't know how to work with pair wise data. 我的问题是我不知道如何使用成对数据。 Ideally, I'd use the type column in the original data frame to assign NAs to all cells containing distances between points of the same type, but I cannot figure out how to do this. 理想情况下,我将使用原始数据帧中的type列将NA分配给包含相同类型点之间距离的所有像元,但我不知道该怎么做。

You can use ?outer , try this: 您可以使用?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