有的時候,我們在數據進行分組時,會發現用正常的聚類分析的方法和思維,分組的情況不是很理想。其實這是因為我們常常會忽略一個問題:假設我們正在分析的數據是真實的,那么它也肯定在一定程度上符合客觀規律。而如果我們正在分析的數據中,有真實的客觀空間數據時,可以考慮用空間自相關的方法去分析。
例如我們在分析城市犯罪率的時候,用聚類分析的思維,我們可能會思考不同城市的犯罪特征是什么,是否有相似點,亦或是試圖把城市分成幾種犯罪模式的歸屬;而如果用空間自相關的思想去看待,問題會變成,高犯罪率的街區在空間上是否聚集或靠近,哪些區域是犯罪率高的熱點區域這種客觀空間上的問題。
以下是一個例子:
# 加載必要的包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的邊緣地帶,數據中有這個特征的在計算時需要額外乘以系數。