I am creating an adjacency matrix to do spatial analysis in R. The data are all counties in the continental US. I've got the counties spatial polygons from US Census Tiger files.
I am able to create the neighbors list, and it is symmetric. But when I convert that to an adjacency matrix it is not symmetric. This is a problem because my goal is to run a spatial autologistic model using ngspatial::autologistic
, and I get an error that I must supply a symmetric binary adjacency matrix.
Here is my R code to create the adjacency matrix:
us<-readShapeSpatial("County_2010Census_DP1.shp")
#Trim out counties outside of continental US
us2<-us[!substr(us$GEOID10,1,2)%in%c('02','60','66','78','15','72'),]
us2.nb = poly2nb(us2)
is.symmetric.nb(us2.nb) #Comes out true
us2.adj = nb2mat(us2.nb, style="B",zero.policy=F)
isSymmetric(us2.adj) #comes out false
As an aside, I am able to use splogit
with this adjacency matrix without a problem. I'm no expert on spatial analysis, so I can't say I know what is going on within these commands.
The matrix
us2.adj
is symmetric. The problem is with the test. It turns out thatuses
all.equal(...)
to test for equality of the matrix with it's transpose, andall.equal(...)
checks the attributes as well as the values.nb2mat(...)
creates a matrix with the row names set to the polygon IDs and the column names unset. Soall.equal(...)
returnsFALSE
and therefore so doesisSymmetric(...)
. Evidently, theautologistic(...)
function uses this same test.The simple solution is to either set the columns names to the row names, or set the row names to
NULL
.BTW, I think the reason this question went unanswered for 18 hours is that you did not provide a link to your shapefile. If you do not provide a reproducible example, the tendency is for members to ignore or downvote the question. See this link for instructions