TransWikia.com

Include ID in an spatial weight matrix R

Geographic Information Systems Asked by Lilia on August 3, 2021

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

PS: This is a repost from a general stackoverflow question (not solve, so far).

One Answer

If you pass your ID'S to the row.names argument in the graph2nb function they will then be assigned as the row/col ids in the Wij matrix.

library(sf)
library(sp)
library(spdep)

data(meuse)
meuse <- meuse[sample(1:nrow(meuse), 26),]
  meuse$IDS <- toupper(paste0(letters))

head(meuse)

meuse <- st_as_sf(meuse, coords = c("x","y"))
col.rel.nb <- graph2nb(relativeneigh(st_coordinates(meuse)), 
                       row.names=meuse$IDS, sym=TRUE)
listaw <- spdep::nb2listw(col.rel.nb, style="W")
  plot(col.rel.nb, coords=st_coordinates(meuse))

Take a look at the matrix

( m <- nb2mat(col.rel.nb) )
  colnames(m) <- rownames(m)
    rownames(m)
    colnames(m)

Correct answer by Jeffrey Evans on August 3, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP