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.
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.