r-spatial / spdep

Spatial Dependence: Weighting Schemes and Statistics
https://r-spatial.github.io/spdep/
123 stars 27 forks source link

Error in nb2listw: Empty neighbour sets found -- But no polygons with 0 neighbors #135

Closed haskellcraigz closed 8 months ago

haskellcraigz commented 1 year ago

Hi, I'm running into a strange problem and haven't been able to find a solution online. I'm looking at the spatial patterning of residuals in a model looking at monitors in texas census tracts. I'm running the following line of code: lm.morantest(m5, listw = tx_nb3_w) where m5 is an OLS model relating monitors ~ tract SES, and tx_nb3_w is the weight matrix of the neighbors list object for texas census tracts (from tx_nb3_w <- nb2listw(tx_nb3, style = "W")).

I get the following error: "Error in nb2listw(neighbours = subnb, glist = NULL, style = style, zero.policy = zero.policy) : Empty neighbour sets found"

However, I shouldn't have any census tracts that don't have any neighbors!

I double check this using summary(tx_nb3) which outputs:

" Neighbour list object: Number of regions: 6236 Number of nonzero links: 36898 Percentage nonzero weights: 0.09488348 Average number of links: 5.916934 Link number distribution:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 16 17 19 59 162 385 821 1249 1357 1002 613 325 144 69 27 14 4 2 2 1 "

I've also been able to run a global moran's I test using the same weight matrix without any problems. (moran.test(tx_sf_data3$log_dist, listw = tx_nb3_w)). There is no missing data in my outcome - but some missing covariates. How does spdep handle such a situation?

Thanks,

rsbivand commented 1 year ago

A minimal reproducible example is essential. Also version of spdep and output of sessionInfo().

rsbivand commented 1 year ago

When covariates have missing values, the spatial weights may be subsetted, leading to no-neighbour observations. Please check whether there any missing values in the data used to fit the regression model.

In lm.morantest(): https://github.com/r-spatial/spdep/blob/85f43d73e3d9bb96fb8db800312c8e3791e52e83/R/lm.morantest.R#L18, then in subset.listw() https://github.com/r-spatial/spdep/blob/85f43d73e3d9bb96fb8db800312c8e3791e52e83/R/subset.nb.R#L56-L57

I repeat that a reproducible example is essential to analyse the problem.