mrc
mrc

Reputation: 21

Converting a normal list into a nb/spdep object in R?

I need to create a neighbours list from a spatial polygon. At the moment i am using the function poly2nb, but unfortunately it is not very accurate, and some polygons with no common points are considered neighbours. I have tried changing the snap argument, but with no luck. I have however tried the function gTouches from the rgeos package, and it works much better. Only problem is, it creates a list object that cannot be used in spdep. Is there any way to convert it into a nb object?

Thank you in advance! :)

Upvotes: 2

Views: 675

Answers (1)

simpson
simpson

Reputation: 335

Looking at the source code for the tri2nb function https://rdrr.io/cran/spdep/src/R/tri2nb.R, which I know is a different function than the one you mentioned, you can change the list to nb type:

class(yourlist) <- "nb"

An example:

mylist <- list(A = c(1,2,5,6), B = c(2,4,6,5))
class(mylist) #check the class of mylist

Initial Result:

> class(mylist)
[1] "list"

Assign the class of mylist as nb

class(mylist) <- "nb"
class(mylist) #check the class of mylist

Final Result:

> class(mylist)
[1] "nb"

From this, you can continue to use functions in spdep to select optimal spatial weighting matrices.

Upvotes: 3

Related Questions