Include ID in an spatial weight matrix R

341 views Asked by At

I have a data frame like this one:

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 )

My main objective is to generate a spatial weight matrix

this is my code so far:

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

The problem is that listaw doesn't include the information in ID. How can I identify each neighbour with the ID (i.e: A,B,C,D,E,F)?

1

There are 1 answers

1
Gray On

This is a great question. This question hasn't been getting the attention it deserves, so I thought I'd give it some focus. Jupyter Lab w/the Rkernel were the IDE used here.

A few changes were made to your dataframe. I replaced the letters in the ID column with integers. And the column names were shortened. The names LATITUDE AND LONGITUDE were shortened to x and y. The redefined df follows:

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

The following code created the sf object, the coordinates matrix, and the nearest neighbors object.

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

The output for n2 follows:

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

The points with links to neighbors get plotted:

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

Finally the weights matrix gets created:

# Create weights matrix
bweights.lw <- nb2listw(n2, style="W", zero.policy=T)
bweights.lw

The plot of the points with links to neighbors (and id's ) at this link: