如何解决在空间权重矩阵R中包含ID
dataSp <- read.table( text = '
ID LATITUDE LONGITUDE
A -85 134
B 34 2
C 42 3
D 45 5
E -2 80
F -5 79',header = TRUE )
我的主要目标是生成空间权重矩阵
到目前为止,这是我的代码:
data_sf <- st_as_sf(dataSp,coords = c("LONGITUDE","LATITUDE"),crs = "+proj=longlat +ellps=wgs84 +datum=wgs84 +no_defs")
st_is_longlat(data_sf)
coords <- st_coordinates(data_sf)
col.rel.nb <- graph2nb(relativeneigh(coords),sym=TRUE)
listaw <- spdep::nb2listw(col.rel.nb,style="W")
问题在于listaw
中没有包含ID
中的信息。如何识别具有ID(即A,B,C,D,E,F)的每个邻居?
解决方法
这是一个很好的问题。这个问题并没有引起应有的重视,所以我想我应该重点关注一下。这里使用的是带有Rkernel的Jupyter Lab。
您对数据框进行了一些更改。我用整数替换了ID列中的字母。并且列名被缩短。纬度和经度名称分别缩写为x和y。重新定义的df如下:
dataSp <- read.table( text = '
id x y
1 -85 134
2 34 2
3 42 3
4 45 5
5 -2 80
6 -5 79',header = TRUE )
dataSp
以下代码创建了sf对象,坐标矩阵和最近的邻居对象。
data_sf <- st_as_sf(dataSp,coords = c("x","y"),crs = "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
coords <- coordinates(as(data_sf,"Spatial"))
n2 <- knn2nb(knearneigh(coords,k=2),row.names=dataSp$id)
n2 # print n2
n2的输出如下:
Neighbour list object:
Number of regions: 6
Number of nonzero links: 12
Percentage nonzero weights: 33.33333
Average number of links: 2
Non-symmetric neighbours list
带有邻居链接的点被绘制:
plot(c(-100,100),c(0,150),type='n',xlab="x",ylab="y",asp=1)
plot(n2,coords,add = TRUE)
text(dataSp$x,dataSp$y,cex=0.7,pos=3)
abline(v=0,col="grey"); abline(h=0,col="grey")
最后创建权重矩阵:
# Create weights matrix
bweights.lw <- nb2listw(n2,style="W",zero.policy=T)
bweights.lw
在此link处具有到邻居(和id)的链接的点的图:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。