给定具有纬度和经度的数据帧,我想添加一个列,该列仅包含在某个半径范围内的其他点(相同数据帧)的计数,例如距离该特定点10公里。
示例数据:
set.seed(1)
radius<-10
lat<-runif(10,-90,90)
long<-runif(10,-180,180)
id<-1:10
dat<-cbind(id,lat,long)
id lat long
[1,] 1 -42.20844 -105.8491530
[2,] 2 -23.01770 -116.4395691
[3,] 3 13.11361 67.3282248
[4,] 4 73.47740 -41.7226614
[5,] 5 -53.69725 97.1429112
[6,] 6 71.71014 -0.8282728
[7,] 7 80.04155 78.3426630
[8,] 8 28.94360 177.0861941
[9,] 9 23.24053 -43.1873354
[10,] 10 -78.87847 99.8802797
现在给定半径变量我想要一个新列说&#34; X&#34;对于每个点,仅包含&#34;半径&#34;内的其他点的数量。我不关心这些是什么点。
虽然此R - Finding closest neighboring point and number of neighbors within a given radius, coordinates lat-long主题和答案已接近,但它并未解决简单计数的具体问题。这个问题不同,因为我需要半径内所有点的计数而不是点
答案 0 :(得分:3)
试试这个:
library(geosphere)
cbind(dat, X=rowSums(distm (dat[,3:2],
fun = distHaversine) / 1000 <= 10000)) # number of points within distance 10000 km
id lat long X
[1,] 1 -42.20844 -105.8491530 5
[2,] 2 -23.01770 -116.4395691 5
[3,] 3 13.11361 67.3282248 5
[4,] 4 73.47740 -41.7226614 6
[5,] 5 -53.69725 97.1429112 4
[6,] 6 71.71014 -0.8282728 6
[7,] 7 80.04155 78.3426630 6
[8,] 8 28.94360 177.0861941 5
[9,] 9 23.24053 -43.1873354 6
[10,] 10 -78.87847 99.8802797 4