以更有效的方式使用 geosphere::distm?

Use the geosphere::distm in a more efficient way?

使用商店的位置数据,我试图找到 'competitors' -- 定义为一定距离内的其他商店。

我正在使用 geo sphere::distm 和一些矩阵运算,如下所示。问题是我的矩阵很大(100,000 X 100,000)并且需要很长时间(或者我的内存不支持这种类型的分析)。有没有办法让下面的代码更有效率?输入文件看起来就像 locations_data(但更大)。所需的输出是数据 table competitors,其中每一行都包含成对的竞争对手。我是在 R 中编写高效代码的新手,想寻求一些帮助。

locations_data<-cbind(id=1:100, longitude=runif(100,min=-180, max=-120), latitude=runif(100, min=50, max=85))

#require(geosphere)
mymatrix<-distm(locations_data[,2:3])

#require(data.table)
analyze_competitors<-function(mymatrix){
    mymatrix2<-matrix(as.numeric(mymatrix<1000000), nrow(mymatrix), ncol(mymatrix)) #
    competitors<-which(mymatrix2==1,arr.ind = T)
    competitors<-data.table(competitors)
    return(competitors)
}

competitors<-analyze_competitors(mymatrix)

如果您想要较小的矩阵,请考虑使用基于经度 and/or 纬度的网格拆分数据。例如,这会生成两个带有 5 x 5 网格标签的新列。

#converting your example data to a tibble.
locations_data<-tibble::as_tibble(locations_data)
#create a numeric grid spanning the extent of your latitude and longitude
locations_data$long_quant<-findInterval(locations_data$longitude, quantile(locations_data$longitude,probs = seq(0,1,.2)), rightmost.closed=TRUE)
locations_data$lat_quant<-findInterval(locations_data$latitude, quantile(locations_data$latitude,probs = seq(0,1,.2)), rightmost.closed=TRUE)

然后您可以使用 locations_data 的子集创建多个较小的矩阵。