R语言 有没有办法找到与纬度/经度点相关的值,这些值落在其他经度/经度点的半径范围内?



我在数据表中有超过 1000 行美国不同社区的经度/经度数据。其中一些社区是竞争对手,另一些是我们自己的。这些社区中的每一个都有许多单元(公寓)。在许多情况下,多个社区彼此相距 3 英里以内。我正在寻找一种方法来执行以下操作:1)确定每个站点是否落在所有其他站点的3英里半径范围内,然后2)将落在该3英里半径内的站点的"单位"列相加。我想在数据表中添加两列...第一列称为"站点数量",第二列称为"单位数量">

我已经编写了代码来检查是否有任何其他纬度/纬度落在彼此的 3 英里半径范围内,但这是我所得到的。

该main_df有 400 多列。为了简化这一点,我重做了以仅显示所需的列。

同名(main_df) 结果:纬度、纬度、单位

所以这个问题中使用的代码将是

main_df<-cbind(main_df, X=((X=rowSums(distm (main_df[,2:1], 
fun = distHaversine) / 1000<= 4.828032)/3)-1))

如前所述,我希望结果将另外两列添加到main_df。 同名(main_df) 结果:纬度、纬度、单位、站点数、单位数

有点像这样...

Lat         Lon      Units  #of Sites   #of Units
40.06127    -86.05604   80    2           184
41.15241    -85.12709   123   3           262
42.91640    -83.62937   125   1           200
39.67114    -86.07211   59    0           0
41.24905    -81.83060   200   4           387

根据我之前的评论:">
我的建议是将 distm 函数的输出保存为变量。 然后,您可以搜索 rowSum> 1 的行,然后使用 what 函数查找附近单位的列(因此是原始数据框的行)。

#Last rows added for testing
main_df<-read.table(header=TRUE, text="Lat    Lon  Units  
40.06127    -86.05604   80
41.15241    -85.12709   123
42.91640    -83.62937   125
39.67114    -86.07211   59
41.24905    -81.83060   200
40.061    -86.056   100
40.060    -86.0561   300")
library(geosphere)
#create and store distance matrix
#this will be a square matrix the length and width of as the number of rows in main_df.
# be aware of memory use.
distmat<-distm (main_df[,2:1], fun = distHaversine)/1000
# convert to logical matrix of units nearby, exclude same location.
distmat<-(distmat >0 & distmat <= 4.828032)
main_df$nearbysites <- rowSums(distmat)
#find rows where there is at least one other nearby sites
rowsnearby<-which(main_df$nearby >0)
#add place holding columns
main_df$sumunits<-0
#loop through all of the rows with more than 1 nearby site
for (i in rowsnearby){
#find columns which are nearby, the column number is the same as the rows of main df that are close by
targetrows<-which(distmat[i,]==TRUE)
#find sum  
main_df$sumunits[i]<-sum(main_df$Units[targetrows])
}
print(main_df)

相关内容

最新更新