You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

空间聚类中消除无邻接数据的R语言解决方法求助

解决Moran检验"Empty neighbour sets found"报错及空间聚类方案

快速处理无邻接选区

你之前的过滤代码无效,是因为nb是邻接列表对象,不是数据框列。用以下方法快速识别并处理孤立选区:

方案1:移除无邻接选区

library(spdep)
library(sf)

# 假设已通过poly2nb生成邻接对象nb
# 找出无邻接的单元索引
no_neighbours <- which(card(nb) == 0)

# 过滤空间数据并重新生成邻接对象
election_filtered_sf <- election_merged_sf[-no_neighbours, ]
nb_filtered <- nb[-no_neighbours]
listw_filtered <- nb2listw(nb_filtered)

# 正常运行Moran检验
Moran_result <- moran.test(election_filtered_sf$participation_rate, listw_filtered)

方案2:给孤立选区添加伪邻接(保留数据)

如果不想删除怀特岛这类选区,可给它们指定邻接:

方法A:自身邻接

nb_filled <- nb
# 给无邻接单元添加自身作为邻接
nb_filled[no_neighbours] <- lapply(no_neighbours, function(x) x)

listw_filled <- nb2listw(nb_filled, style="W")
Moran_result <- moran.test(election_merged_sf$participation_rate, listw_filled)

方法B:绑定最近选区作为邻接

# 计算选区中心点
centroids <- st_centroid(election_merged_sf)
dist_matrix <- st_distance(centroids)

nb_filled <- nb
# 给每个孤立选区找最近的非自身选区
for(i in no_neighbours){
  closest <- which(dist_matrix[i, ] == min(dist_matrix[i, ][-i]))[1]
  nb_filled[[i]] <- closest
}

listw_filled <- nb2listw(nb_filled)
Moran_result <- moran.test(election_merged_sf$participation_rate, listw_filled)

替代空间聚类方法(匹配你的目标)

除了Moran检验,这些方法可直接获取参与率相似的空间聚类:

1. 空间层次聚类(SKATER)

保证聚类内部的空间连续性:

# 基于过滤后的邻接对象运行
data_matrix <- as.matrix(election_filtered_sf$participation_rate)
skater_result <- skater(nb_filtered, data_matrix, ncuts=5) # 自定义聚类数量

# 给数据框添加聚类结果
election_filtered_sf$skater_cluster <- skater_result$groups

2. 局部Moran's I(LISA)

识别高-高、低-低等显著空间聚类:

lisa_result <- localmoran(election_filtered_sf$participation_rate, listw_filtered)

# 标记聚类类型
election_filtered_sf$lisa_cluster <- factor(
  ifelse(lisa_result$Ii > 0 & lisa_result$Pr(z <= 0) < 0.05, "高参与率聚类",
         ifelse(lisa_result$Ii < 0 & lisa_result$Pr(z >= 0) < 0.05, "低参与率聚类",
                "无显著聚类"))
)

3. DBSCAN密度聚类

适合非连续的相似区域:

library(dbscan)
centroid_coords <- st_coordinates(st_centroid(election_filtered_sf))
# eps为距离阈值(单位米,根据数据调整),minPts为聚类最小单元数
dbscan_result <- dbscan(centroid_coords, eps=50000, minPts=3)

election_filtered_sf$dbscan_cluster <- dbscan_result$cluster

内容的提问来源于stack exchange,提问作者Oscar Hill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 00:10:36