r计算莫兰 I 检验空间自相关的问题



我在使用 R 计算空间自相关的 Moran I 检验时遇到问题。

我做了以下工作:

#I download all the appropriate libraries 
    library(maptools) 
    library(spdep) 
    library(splancs) 
    library(spatstat)
    library(pwt)
#i import my shapefile and I calculate the coordinates
serbia<-readShapePoly("SRB_adm1")
coords<-coordinates(serbia)

#i created a weigthed matrix using the above definition of neigbour(dnb60 object)
dnb60.listw<-nb2listw(dnb60,style="W", zero.policy=F)
#i import my dataset which contains around 500 variables and is a firm level dataset containing 2373 firms.
library(foreign)
statafile<-read.dta("path", missing.type = T, warn.missing.labels = T) 
#i combine the shapefile(serbia) with the imported dataset(statafile) and created file with coordiantes (new) using common variable ID_1(region code). My final dataset is data_total.
new<- cbind(coordinates(serbia), serbia$ID_1)
newdata <- data.frame(new)
names(newdata)<-c("X", "Y", "ID_1")
cis_08_10 <- merge(statafile, serbia, by="ID_1", all.x=T)
data_total<-merge(cis_08_10, newdata, by="ID_1",all.x=T)

我对最终数据集data_total中特定变量prod_ser计算的Moran I测试感兴趣。

我做了以下工作:

#calculating Moran I test
moran.test(data_total$prod_ser, dnb60.listw, randomisation=F)
I get the following error: Error in moran.test(data_total$prod_ser, dnb60.listw, randomisation = F) : 
  objects of different length

现在,data_total$prod_ser的长度为 2373,dnb60.listw的长度为 3。我认为主要问题是W矩阵是使用包含 25 个区域的 serbia shapefile 创建的,而prod_ser变量是来自拥有 2373 家公司data_total的公司级变量(我想这应该对应于点数据,公司是点(。

为什么合并数据集没有帮助?我还需要做什么来计算莫兰一世而没有这个错误?

好吧!您自己已经确定了问题。这正是您出现此类错误的原因。'dnb60.listw' 基于数据集塞尔维亚,由于您在 moran.test 公式中使用了"数据总计",因此您会收到此类错误。您应该首先合并数据,然后根据合并的数据估计"dnb60.listw",然后计算Moran I。你应该没事的。

附言我不是R方面的专家,英语也不是我的第一语言,因此,如果有任何误解,我

提前道歉:)

问题是两个数据集是不同的。对我有用的是:

  1. 首先,创建 W 矩阵。
nbk <- knn2nb(knearneigh(st_centroid(dnb60)))
  1. 其次,将其转换为列表:
dnb60.listw<-nb2listw(dnb60,style="W", zero.policy=F)
  1. 检查所有长度是否相同
length(dnb60) 
length(nbk)
length(dnb60.listw) 

由于我没有您的数据,因此我无法重现确切的示例,但是如果您运行此部分,您应该会发现所有这 3 个长度都是不同的。它们应该是相同的,以便您可以运行莫兰测试

溶液?我要做的是先运行合并。确保所有数据集具有相同数量的观测值。然后,使用我在步骤 3 中提供的长度进行检查,然后运行 Moran 测试。

我希望这有帮助!

最新更新