Skip to content
Prev 26640 / 29559 Next

nb object in spdep from categorical attribute

On Tue, 19 Jun 2018, Dexter Locke wrote:

            
Yes, spdep::nb2blocknb() is a specific case where say observations without 
positional data are known to belong to an aggregate entity for which we 
have positional data. The output is an nb object with diagonal blocks (if 
the observations are sorted by block ID, not in the case below), as this 
example shows. You'll need the development version to run it, as released 
spdep::aggregate.nb() failed with empty aggregate sets - the nc median 
poish grid has such empty sets:

# devtools::install.github("r-spatial/spdep")
library(spdep)
data(nc.sids)
ncCC89.nb[sapply(ncCC89.nb, length) == 0L] <- 0L
image(as(nb2listw(ncCC89.nb, zero.policy=TRUE), "CsparseMatrix"))
anb <- aggregate(ncCC89.nb, interaction(nc.sids$M.id, nc.sids$L.id))
image(as(nb2listw(anb, style="B"), "CsparseMatrix"))
# when the neighbour object is not empty
bnb <- nb2blocknb(anb, as.character(interaction(nc.sids$M.id,
   nc.sids$L.id)))
image(as(nb2listw(bnb, style="B"), "CsparseMatrix"))
# and when the neighbour object is empty
anb1 <- lapply(anb, function(x) x <- 0L)
attributes(anb1) <- attributes(anb)
bnb1 <- nb2blocknb(anb1, as.character(interaction(nc.sids$M.id,
   nc.sids$L.id)))
image(as(nb2listw(bnb1, style="B"), "CsparseMatrix"))

This isn't your case, but crafting an nb object by hand (adding 
attributes after creating the list) then using spdep::union.nb or similar 
to combine with a positional nb (such as poly2nb) may work. For parcels 
across a stream or street, maybe look at the snap= argument if the streets 
are narrower than frontages. Could you provide a small reproducible 
example?

Hope this clarifies,

Roger