1

我有一个像这样的数据框:

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)?

4

1 回答 1

1

这是一个很好的问题。这个问题没有得到应有的关注,所以我想我应该重点关注一下。带有 Rkernel 的 Jupyter Lab 是这里使用的 IDE。

对您的数据框进行了一些更改。我用整数替换了 ID 列中的字母。并且列名被缩短了。名称 LATITUDE 和 LONGITUDE 缩短为 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

在此链接上与邻居(和 id 的)链接的点图:

于 2020-09-19T08:20:33.413 回答