1

I am trying to construct a spatial weight matrix from shapefile (.shp) in R. The thing is, I don't even have any single idea how to do it. And I am having trouble finding any reference. Most of the tutorial I find only describing about how to work with shapefile/map in general or they use an already available neighborhood list (ex. columbus.nb).

Any help will be really appreciated. Thanks in advance.

  • Maybe this [post](http://stackoverflow.com/questions/27304797/r-spatial-weights-asymmetric-adjacency-matrix) will be a start. – lmo May 27 '16 at 16:49

2 Answers2

1

I hope the following code may help:

shapefile <- rgdal::readOGR(“shapefile_file.shp”)
coordinatess <- sp::coordinates(shapefile)
shapefile.knn <- spdep::knearneigh(coordinatess, k = number_of_shapefile_rows)
shapefile.nb <- spdep::knn2nb(shapefile.knn)

#list:
dist <- spdep::nbdists(shapefile.nb,coordinates)
dist2 <- lapply(dist, function(x) 1/(x^2)) 

#listw:
dist2.listw <- spdep::nb2listw(shapefile.nb, glist=dist2)

#matrix:
dist2.mat <- spdep::listw2mat(dist2.mat)

It creates inverted squared distance matrix - in my opinion often the best choice in spatial econometrics. It may be easily changed to get k nearest neighbours matrix or inverted distance matrix.

Required packages are written before the '::' operator. You need to install them.

cure
  • 425
  • 2
  • 12
0

I think that this code line

dist2.mat <- spdep::listw2mat(dist2.mat)

has an error, it should be

listw2mat(dist2.listw ) 

instead

buddemat
  • 4,552
  • 14
  • 29
  • 49