Skip to content
Prev 733 / 29559 Next

subset grid and neighbour list

On Mon, 9 Jan 2006, Ronnie Babigumira wrote:

            
library(spdep)
set.seed(20060110)
input <- data.frame(expand.grid(x=1:10, y=1:10), z=rpois(100, 3))
coordinates(input) <- c("x", "y")
table(input$z)
is.na(input$z) <- input$z < 1 | input$z > 5
table(input$z)
input$z <- as.factor(input$z)
rook <- dnearneigh(coordinates(input), 0, 1)
rook
plot(rook, coordinates(input))
joincount.multi(input$z, nb2listw(rook, 
style="B"))
# Error in joincount.multi(input$z, nb2listw(rook, style = "B")) : 
#        NA in factor
keep <- !is.na(input$z)
rook_sub <- subset(rook, subset=keep)
input_sub <- subset(input, subset=keep)
rook_sub
# look out for no-neighbour cells - if present, use zero.policy=TRUE below
plot(rook_sub, coordinates(input_sub))
joincount.multi(input_sub$z, nb2listw(rook_sub, style="B"))

This is for a full grid, but if you have SpatialPixels or SpatialPolygons 
the order of operations will be the same, I think. You need to watch out 
for no-neighbour cells after subsetting, and use zero.policy=TRUE in both 
joincount.multi() and nb2listw() if they have been introduced.

Roger