4

I need some help to finalize code for a spatial weight matrix that uses a nearest neighbor definition within regions, but does not allow neighbors from across a political border. For example, physically adjacent counties are neighbors, but physically adjacent counties separated by a state boundary are not neighbors.

I am working with an ESRI shapefile, with about 40,000 polygons.

The nearest neighbor bit is straightforward using functions from spdep. And I have collected a code example that creates a boundary effect:

# xxx is the name of the shape file

unique(xxx$country)
length(unique(xxx$countrycode))

# B_domestic = Indicator function taking value 1 if two regions belong to  same          country and 0 if not

B_domestic <- bdiag(
        matrix(1,length(xxx$countrycode[xxx$countrycode=="001"]),
            length(xxx$countrycode[xxx$countrycode=="001"]))
        matrix(1,length(xxx$countrycode[xxx$countrycode=="002"]),
            length(xxx$countrycode[xxx$countrycode=="002"])),

##  and so on .  . .
##  then check the object generated

dim(B_domestic)
class(B_domestic)

##  convert it to a matrix
B_domestic <- as.matrix(B_domestic)

## then the matrix is converted to a list W object 

B_domestic_listW <- mat2listw(B_domestic); class(B_domestic_listW)

## and back to a weights object (I think? documentation is pretty sparse)

B_domestic_2 <- as_dgRMatrix_listw(B_domestic_listW)

It seems that the something from this process then becomes an argument for creating the nearest neighbors, but what is the cleanest way to do this? And in which function?

Using spdep, I have:

data4NN <-  knn2nb(knearneigh(coords, k=4), row.names = ID)
##row-standardized

W.list <- nb2listw(data4NN,style="W")
summary(W.list)

where coords are the previously generated centroid coordinates of my original polygon file, and ID is a unique identifier in the polygon file; 4 nearest polygons are neighbors.

Object W.list then becomes the object used in my spatial regression specification (SAR,SD,SEM)

I feel like I have the pieces, but don't understand how they relate to one another to get the outcome I'm looking for. Specifically, where does the argument to limit the adjacency by the political boundary fit into generating a nearest-neighbors spatial weight matrix?

  • I have the same question. Please someone respond. – dgee Jun 19 '17 at 16:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.