Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 基于纬度和经度获取K个最近邻_R_Dplyr_Tidyverse_Tidy - Fatal编程技术网

R 基于纬度和经度获取K个最近邻

R 基于纬度和经度获取K个最近邻,r,dplyr,tidyverse,tidy,R,Dplyr,Tidyverse,Tidy,我有不同点的经纬度数据。这是我的数据的简单版本: # Add library library(tidyverse) # Generate data distance <- tibble( location = c("first", "second", "third"), lat = c(33.720792, 33.715187, 33.714848), long = c(-84.468126, -84

我有不同点的经纬度数据。这是我的数据的简单版本:

# Add library
library(tidyverse)

# Generate data
distance <-
  tibble(
    location = c("first", "second", "third"),
    lat = c(33.720792, 33.715187, 33.714848),
    long = c(-84.468126, -84.468684, -84.454265)
  ) 
#添加库
图书馆(tidyverse)
#生成数据

距离软件包
geodist
中的
geodist
函数计算纬度和经度指定的点之间的距离,即

library(geodist)
geodist(distance)

#          [,1]      [,2]     [,3]
#[1,]    0.0000  625.0321 1441.547
#[2,]  625.0321    0.0000 1333.401
#[3,] 1441.5466 1333.4007    0.000
然后可以按行排序,以提供输出

apply(geodist::geodist(distance),1,function(x)distance$location[order(x)])
#     [,1]     [,2]     [,3]    
#[1,] "first"  "second" "third" 
#[2,] "second" "first"  "second"
#[3,] "third"  "third"  "first" 
如果需要,可以使用
data.frame()
和设置
colnames
对输出进行格式化


如果可能存在重复项,则需要从排序中明确排除前导对角线,并从输入数据中复制
位置
列。

您可以使用FNN包查找k近邻。它可以很好地处理大量数据,因此即使使用大型数据集,您也应该能够通过以下代码找到完整的排名:

#添加库
图书馆(tidyverse)
图书馆(FNN)
#>警告:R版本4.0.4下的pakke'FNN'blev bygget
#生成数据
距离%
get.knn(k=nrow(.)-1)
knn
#>$nn.index
#>      [,1] [,2]
#> [1,]    2    3
#> [2,]    1    3
#> [3,]    2    1
#> 
#>$nn.dist
#>             [,1]       [,2]
#> [1,] 0.005632707 0.01508173
#> [2,] 0.005632707 0.01442298
#> [3,] 0.014422985 0.01508173
#确定地点
loc[2,]第一个“第三个”
#>[3,]第二个“第一个”
#最终数据
距离%>%
选择(位置)%>%
绑定列(loc%>%as_tible())
#>#tibble:3 x 3
#>位置邻居1邻居2
#>                    
#>1第一秒第三
#>2秒1秒3
#>3第三秒第一

由(v0.3.0)于2021-03-25创建

也许这对您有用:有趣的方法!但是,请注意,根据投影坐标系,“数学”距离与地理距离不同。可能需要先将坐标转换为等面积或等距离投影。
apply(geodist::geodist(distance),1,function(x)distance$location[order(x)])
#     [,1]     [,2]     [,3]    
#[1,] "first"  "second" "third" 
#[2,] "second" "first"  "second"
#[3,] "third"  "third"  "first"