r - 如何将位置分配为聚类质心并运行聚类以找到离每个质心最近的点?
问题描述
使用质心坐标作为质心,并根据最近的位置对它们周围的其余位置进行聚类。
Centroid <- data.frame (longitude =c( -1.482880, -1.485735),
latitude = c( 54.89935, 54.89935),
ID = c(1,2,3,4,5))
Locations <- data.frame(longitude = c(-1.482156, -1.482318, -1.482129, -1.484275, -1.485866),
latitude= c(54.90083, 54.90078, 54.90077, 54.90011, 54.89936),
ID = c(A,B,C,D,E))
解决方案
使用 sf 包查找离位置最近的质心相对容易。您需要将数据框转换为 sf 对象,如下所示。
library(tidyverse)
library(sf)
#> Linking to GEOS 3.6.2, GDAL 2.2.3, PROJ 4.9.3
centroid <- data.frame (longitude =c( -1.482880, -1.485735),
latitude = c( 54.89935, 54.89935),
ID = c(1,2))
locations <- data.frame(longitude = c(-1.482156, -1.482318, -1.482129, -1.484275, -1.485866),
latitude= c(54.90083, 54.90078, 54.90077, 54.90011, 54.89936),
ID = c(LETTERS[1:5]))
# 4326 is common, but a poor choice for accurate distances. you should choose a better crs.
cen_sf <- st_as_sf(centroid, coords = c('longitude', 'latitude')) %>% st_set_crs(4326)
loc_sf <- st_as_sf(locations, coords = c('longitude', 'latitude')) %>% st_set_crs(4326)
st_nearest_feature(loc_sf, cen_sf)
#> although coordinates are longitude/latitude, st_nearest_feature assumes that they are planar
#> [1] 1 1 1 1 2
st_distance(loc_sf, cen_sf)
#> Units: [m]
#> [,1] [,2]
#> [1,] 171.1779 282.59946
#> [2,] 163.2218 270.91505
#> [3,] 165.2558 280.18680
#> [4,] 123.1550 126.21773
#> [5,] 191.5677 8.47761
由reprex 包于 2020-01-16 创建(v0.3.0)
推荐阅读
- algorithm - 查找给定 x 值的多项式序列
- google-app-engine - 多区域云存储费用
- c# - C# winforms 为什么消息框不适用于 DataReader 的 IF
- python - 有什么方法可以更有效地/用更少的代码打印“年”或“年”?
- node.js - 当我从节点中的条带中删除我的帐户时,它会出现一些错误
- c++ - 文件大小适中的构建挂起
- android - 启动模拟器时 Android SDK 实例错误
- javascript - 使用 addeventlistener 删除动态生成的元素
- linux - 在 Makefile 中创建一个 spawn shell
- node.js - 如何在 node.js 的函数中使用 If 语句设置全局变量?