r-spatial / spdep

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

is the number returned by poly2nb() function representing the order of the data #125

Closed xu003822 closed 1 year ago

xu003822 commented 1 year ago

Hi everyone,

I am using poly2nb() to find neighbors for municipalities in NJ, USA. When I used poly2nb(), it returns, for example one of the rows is: [[1]] integer [4] 16 143 186 426

I am wondering whether this "[[1]]" corresponds to the first observation of my dataset? and "16" corresponds to the 16th observation of the dataset.

Thanks a lot!

rsbivand commented 1 year ago

Please provide an example with code and do use built in data sets. It is not possible to see what you are puzzled by from this description. Did you read either vignette about nb objects?

library(spdep)
data(columbus, package="spData")
col.gal.nb[[1]]
## [1] 2 3
2:3
## [1] 2 3

col.gal.nb[[1]] lists the first integer vector in the list of neighbours, just like 2:3, [1] says that the left number is the first in the vector.

2:30
##  [1]  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
## [26] 27 28 29 30

For longer vectors, the square bracket contains the sequence index of the left number along the vector.

The nb object is a list of vectors, so listing the first three list components, the double square brackets say which list component it is (the "from" neighbour), and the integer vector the "to" neighbours:

col.gal.nb[1:3]
## [[1]]
## [1] 2 3
## 
## [[2]]
## [1] 1 3 4
## 
## [[3]]
## [1] 1 2 4 5

If we convert to weights, and on to a data.frame of from.to,weights triplets, this may be clearer:

head(listw2sn(nb2listw(col.gal.nb, style="B")))
##   from to weights
## 1    1  2       1
## 2    1  3       1
## 3    2  1       1
## 4    2  3       1
## 5    2  4       1
## 6    3  1       1

nb objects are sparse graph/matrix representations of the relationships, and are efficient in stoorage and processing (they do not record which j are not neighbours of i).