R中的空间聚类(简单示例)

时间:2015-02-23 11:11:56

标签: r geospatial spatial hierarchical-clustering

我有这个简单的data.frame

 lat<-c(1,2,3,10,11,12,20,21,22,23)
 lon<-c(5,6,7,30,31,32,50,51,52,53)
 data=data.frame(lat,lon)

我们的想法是根据距离

找到空间聚类

首先,我绘制地图(lon,lat):

plot(data$lon,data$lat)

enter image description here

很明显我有三个基于点位置之间距离的聚类。

为此目的,我在R:

中尝试了这段代码
d= as.matrix(dist(cbind(data$lon,data$lat))) #Creat distance matrix
d=ifelse(d<5,d,0) #keep only distance < 5
d=as.dist(d)
hc<-hclust(d) # hierarchical clustering
plot(hc)
data$clust <- cutree(hc,k=3) # cut the dendrogram to generate 3 clusters

这给出了:

enter image description here

现在我尝试使用群集中的颜色绘制相同的点

plot(data$x,data$y, col=c("red","blue","green")[data$clust],pch=19)

结果

enter image description here

这不是我正在寻找的。

实际上,我想找到类似这个情节的内容

enter image description here

感谢您的帮助。

3 个答案:

答案 0 :(得分:10)

这样的事情:

lat<-c(1,2,3,10,11,12,20,21,22,23)
lon<-c(5,6,7,30,31,32,50,51,52,53)

km <- kmeans(cbind(lat, lon), centers = 3)
plot(lon, lat, col = km$cluster, pch = 20)

enter image description here

答案 1 :(得分:7)

这是一种不同的方法。首先,它假设坐标是WGS-84而不是UTM(平坦)。然后,它使用层次聚类(使用方法= single将给定半径内的所有邻居聚类到同一群集,该方法采用朋友的朋友聚类策略)。

为了计算距离矩阵,我使用了包rdist.earth中的fields方法。此软件包的默认地球半径为6378.388(赤道半径),可能不是人们想要的,所以我已将其更改为6371.有关详细信息,请参阅this article

library(fields)
lon = c(31.621785, 31.641773, 31.617269, 31.583895, 31.603284)
lat = c(30.901118, 31.245008, 31.163886, 30.25058, 30.262378)
threshold.in.km <- 40
coors <- data.frame(lon,lat)

#distance matrix
dist.in.km.matrix <- rdist.earth(coors,miles = F,R=6371)

#clustering
fit <- hclust(as.dist(dist.in.km.matrix), method = "single")
clusters <- cutree(fit,h = threshold.in.km)

plot(lon, lat, col = clusters, pch = 20)

如果您不知道群集的数量(如k-means选项),这可能是一个很好的解决方案,并且与minPts = 1的dbscan选项有些相关。

--- --- EDIT

使用原始数据:

lat<-c(1,2,3,10,11,12,20,21,22,23)
lon<-c(5,6,7,30,31,32,50,51,52,53)
data=data.frame(lat,lon)

dist <- rdist.earth(data,miles = F,R=6371) #dist <- dist(data) if data is UTM
fit <- hclust(as.dist(dist), method = "single")
clusters <- cutree(fit,h = 1000) #h = 2 if data is UTM
plot(lon, lat, col = clusters, pch = 20)

答案 2 :(得分:5)

由于您有要进行群集的空间数据,因此DBSCAN最适合您的数据。 您可以使用fpc提供的dbscan()函数执行此群集, R 包。

library(fpc)

lat<-c(1,2,3,10,11,12,20,21,22,23)
lon<-c(5,6,7,30,31,32,50,51,52,53)

DBSCAN <- dbscan(cbind(lat, lon), eps = 1.5, MinPts = 3)
plot(lon, lat, col = DBSCAN$cluster, pch = 20)

Plot of DBSCAN Clustering

相关问题