r-spatial / spdep

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

something wrong with nb2listw #150

Closed huangcx1539 closed 2 months ago

huangcx1539 commented 2 months ago

get a error with "Error in nb2listw(neighbor_list, style = "W") : Not a neighbours list"

library(spdep) adj_matrix <- matrix(c(0, 1, 1,0, 1, 0, 1,1, 1, 1, 0,0, 0, 1, 0,0), nrow=4, byrow=TRUE)

neighbor_list <- lapply(1:nrow(adj_matrix), function(i) which(adj_matrix[i, ] == 1)) neighbor_list colw <- nb2listw(neighbor_list,style="W")

get a error with "Error in nb2listw(neighbor_list, style = "W") : Not a neighbours list"

rsbivand commented 2 months ago

Nothing wrong with the function. It is always a bad idea to hand-create nb objects, they should be created from the input geometries, and in those cases nb2listw works. If you have to use a matrix, use:

> mat2listw(adj_matrix, style="W")
Characteristics of weights list object:
Neighbour list object:
Number of regions: 4 
Number of nonzero links: 8 
Percentage nonzero weights: 50 
Average number of links: 2 

Weights style: W 
Weights constants summary:
  n nn S0       S1   S2
W 4 16  4 4.166667 17.5

If the matrix also has row or/and column IDs, these will feed through too.

huangcx1539 commented 2 months ago

mat2listw can solve the above problem, and the conversion of the input adjacency matrix into an adjacency list cannot be accepted by nb2listw