I am attempting to create a neighborhood matrix (poly2nb in spdep) in R to use either for a GAM or an INLA.

As I have spatio-temporal data, counties appear multiple times over time. However, there is not always data available for every county in every year. In order for the neighborhood matrix to work in R, I need to delete the rows with NAs. As neighborhood does not change over time, my attempt was to create a neighborhood matrix with the unique county ids and unique geometries (polygons). In my opinion, it would not make sense to make to include the same county twice if the overall neighborhood stays the same over time. This approach worked with GAM. I included the unique neighborhood matrix and included a dummy matrix for years.

However, INLA is not satisfied with the unique values. But otherwise, a county would have the same neighbors multiple times in the matrix. This might be unproblematic, however I am lacking insights.


Ignore the temporal aspect of the data, for now. What you want to generate is a neighbour matrix for the counties. You proceed to create this matrix in the same way as if you only had a single observation from each county.

In the GAM (assuming mgcv here) context, you will have a factor variable in the full spatiotemporal data set you want to use for modelling that will contain the county labels. These will of course contain repeated instances of the $c$ county labels. What you want to end up with for mgcv's mrf basis is a neighbour matrix for the $c$ counties only as it generates the full penalty for the data by indexing into the $c$ by $c$ penalty matrix using the labels of the counties.

As you have a set of polygons for the counties, create the neighbour matrix from the polygon object using poly2nb. mgcv should be able to work with that.

spdep also contains a function nd2INLA() to create the adjacency matrix (neighbour matrix) from the nb representation.

The example from ?nd2INLA is:

td <- tempdir()
x <- nb2INLA(paste(td, "columbus-INLA.adj", sep="/"), col.gal.nb)

where the first line loads some example data from Columbus, Ohio, including a neighbour matrix col.gal.nb. We can ignore the second line (this is just using a temporary folder to write the data to during package checks).

The third line contains the important stuff; the first argument to nb2INLA is the filename where you want the adjacency (neighbour) matrix written to, whilst the second argument is the nb object you want to convert to the required INLA format.


Your Answer

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