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)?
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:
The following code created the sf object, the coordinates matrix, and the nearest neighbors object.
The output for n2 follows:
The points with links to neighbors get plotted:
Finally the weights matrix gets created:
The plot of the points with links to neighbors (and id's ) at this link: