有的时候,我们在数据进行分组时,会发现用正常的聚类分析的方法和思维,分组的情况不是很理想。其实这是因为我们常常会忽略一个问题:假设我们正在分析的数据是真实的,那么它也肯定在一定程度上符合客观规律。而如果我们正在分析的数据中,有真实的客观空间数据时,可以考虑用空间自相关的方法去分析。
例如我们在分析城市犯罪率的时候,用聚类分析的思维,我们可能会思考不同城市的犯罪特征是什么,是否有相似点,亦或是试图把城市分成几种犯罪模式的归属;而如果用空间自相关的思想去看待,问题会变成,高犯罪率的街区在空间上是否聚集或靠近,哪些区域是犯罪率高的热点区域这种客观空间上的问题。
以下是一个例子:
# 加载必要的包library(spdep)
library(sp)
library(ggplot2)# 设置随机种子保证结果可重复
set.seed(123)# 1. 创建空间网格数据
grid_size <- 10
coords <- expand.grid(x = 1:grid_size, y = 1:grid_size)# 2. 构建空间权重矩阵(4个最近邻)
nb <- knn2nb(knearneigh(as.matrix(coords), k = 4))
listw <- nb2listw(nb, style = "W")# 3. 生成空间自相关数据(替代方法)
rho <- 0.7
y <- rnorm(grid_size^2) # 初始随机数据
for(i in 1:10){ y <- rho * lag.listw(listw, y) + y # 迭代增强空间自相关
}# 4. 创建数据框(此时y已生成)
spatial_data <- data.frame(x = coords$x,y = coords$y,value = scale(y) # 标准化数据
)# 5. 可视化结果
ggplot(spatial_data, aes(x, y, fill = value)) +geom_tile() + scale_fill_viridis_c() +labs(title = paste("空间自相关数据 (rho =", rho, ")"),subtitle = "颜色越黄表示值越高") +theme_minimal()# 计算空间权重矩阵
coords_mat <- as.matrix(spatial_data[, c("x", "y")])
nb <- knn2nb(knearneigh(coords_mat, k = 4))
listw <- nb2listw(nb, style = "W")# 计算Moran's I
moran_test <- moran.test(spatial_data$value, listw)
print(moran_test)# 结果解读:
# Moran I statistic > 0 表示正空间自相关(聚集)
# p-value < 0.05 表示空间自相关显著# 计算局部Moran's I
local_moran <- localmoran(spatial_data$value, listw)# 将结果添加到数据中
spatial_data$local_i <- local_moran[, "Ii"]
spatial_data$p_value <- local_moran[, "Pr(z != E(Ii))"]# 可视化局部空间自相关
ggplot(spatial_data, aes(x, y, fill = local_i)) +geom_tile() +scale_fill_gradient2(low = "blue", mid = "white", high = "red") +theme_minimal() +ggtitle("局部Moran's I值")# 显示显著的热点(p < 0.05)
spatial_data$significant <- spatial_data$p_value < 0.05
ggplot(spatial_data, aes(x, y, fill = significant)) +geom_tile() +scale_fill_manual(values = c("TRUE" = "red", "FALSE" = "gray")) +theme_minimal() +ggtitle("显著的空间自相关区域(p < 0.05)")
输出:
Moran I test under randomisationdata: spatial_data$value
weights: listw Moran I statistic standard deviate = 12.836, p-value < 2.2e-16
alternative hypothesis: greater
sample estimates:
Moran I statistic Expectation Variance 0.858001632 -0.010101010 0.004573975
Moran's值为0.858接近1,表明结果是强正空间相关的,p小于0.05更加强了结果的说服性,而图中所显示的说明重点区域多在横轴大于7.5的边缘地带,数据中有这个特征的在计算时需要额外乘以系数。