Search code examples
rspatialspdep

Extract spatial ids from weights list object, spdep R


I have used mat2listw{spdep} to create a weights list object that I will later use in a spatial regression. I would like to retrieve from this weights list object the ids of the polygons used to create it. Is it possible to recover this info from the object?

Here is a reproducible example:

library(spdep)
library(UScensus2000tract)

# load data
  data("oregon.tract")

# get coordinates of centroids
  coords <- coordinates(oregon.tract)

# calculate a simple distance matrix between coordinates
  d <- dist(coords) 
  d <- as.matrix(d)

# Calculate Spatial weights Matrix (travel time)
  my_weights <- mat2listw(d, row.names = row.names(oregon.tract))

# Now I'd like to extract from my_weights the polygon ids

Solution

  • library(spdep)
    library(UScensus2000tract)
    
    # load data
      data("oregon.tract")
    
    # get coordinates of centroids
      coords <- coordinates(oregon.tract)
    
    # calculate a simple distance matrix between coordinates
      d <- dist(coords) 
      d <- as.matrix(d)
    
    # Calculate Spatial weights Matrix (travel time)
      my_weights <- mat2listw(d, row.names = row.names(oregon.tract))
    
    # Extract region ids from attributes of my_weights
    region.ids <- attributes(my_weights)$region.id
    
    head(region.ids)
    [1] "oregon_0" "oregon_1" "oregon_2" "oregon_3" "oregon_4" "oregon_5"