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

如何解决R语言空间自相关中‘dimnames长度与数组范围不匹配’错误

局部空间自相关分析(Local Moran's I)报错排查与解决

我正在用R语言开展基于Local Moran's I统计量的局部空间自相关分析,邻域查找、邻域转listw对象的代码均可正常运行,但全局模型和局部模型先后出现报错,具体场景及解决方案如下:

1. 全局模型初始报错及修复

初始代码

setwd("H:/R")
library("sf")
library("sp")
library("spdep")
library("rgdal")
library("rgeos")
library("ggplot2")
library("tmap")
OA.Census<- readOGR(".","Kenya")

RC.neighbours <- poly2nb(OA.Census, queen = FALSE) #采用Rook规则识别邻域
listw<- nb2listw(RC.neighbours, zero.policy =TRUE)  #将邻域数据转为listw对象
moran.test(OA.Census$Population,listw, zero.policy= TRUE)

报错信息

Error in moran.test(OA.Census$Population, listw, zero.policy = TRUE) : 
  OA.Census$Population is not a numeric vector

修复方法

将Population列转换为数值向量后,全局模型运行正常:

Pop <- as.numeric(OA.Census$Population)
moran.test(Pop,listw, zero.policy= TRUE)

运行结果

Moran I test under randomisation

data:  Pop  

weights: listw  n reduced by no-neighbour observations
  

Moran I statistic standard deviate = 2.9727, p-value = 0.001476
alternative hypothesis: greater
sample estimates:
Moran I statistic       Expectation          Variance 
      0.227104264      -0.022222222       0.007034374 

2. 局部模型报错及解决方案

报错代码

moran<- moran.plot(Pop, listw =nb2listw(RC.neighbours,zero.policy= TRUE, style = "W"))

报错信息

Error in dimnames(x) <- dn : 
  length of 'dimnames' [1] not equal to array extent
In addition: Warning message:
In lag.listw(listw, x, zero.policy = zero.policy) : NAs in lagged values

问题根源

报错核心是无邻域的孤立空间要素导致维度不匹配:zero.policy=TRUE允许程序处理孤立要素,但moran.plot在计算滞后值时,孤立要素会生成NA,进而引发维度名称与数组范围不匹配的错误。

解决步骤

步骤1:定位孤立要素

先找出数据中没有邻域的要素:

# 查看每个要素的邻域数量
neigh_count <- card(RC.neighbours)
# 获取孤立要素的索引
no_neigh_idx <- which(neigh_count == 0)

步骤2:清理数据并重构空间权重

移除孤立要素(更符合空间自相关分析逻辑),重新计算邻域与listw对象:

# 移除无邻域的要素
OA.Census_clean <- OA.Census[-no_neigh_idx, ]
# 重新识别邻域
RC.neighbours_clean <- poly2nb(OA.Census_clean, queen = FALSE)
# 重构listw对象
listw_clean <- nb2listw(RC.neighbours_clean, style = "W")
# 提取对应数值列
Pop_clean <- as.numeric(OA.Census_clean$Population)

步骤3:重新运行局部Moran绘图

moran.plot(Pop_clean, listw = listw_clean)

内容的提问来源于stack exchange,提问作者Cheruiyot Vincent

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 20:10:31