r - listing and plotting nearest neighbours using the spdep package

572 views Asked by At

It's my first using the spdep package in R so I was hoping someone could help me with a few things.

Let's consider the following points.

set.seed(1)
loc <- data.frame(id=1:15,
                  x=sample(-10:10,15,replace=TRUE),
                  y=sample(-10:10,15,replace=TRUE))
plot(loc[,-1],asp=1)
text(loc$x, loc$y, cex=0.7, pos=3)

Essentially, I want to construct paths by connecting points which are closest to each other. For example, if we want paths of length 3 and we start at point 1, then we should go to point 11 next, then finally point 10. Here are the other the paths which I got manually.

      [,1] [,2] [,3]
[1,]     1   11   10
[2,]     2    5   14
[3,]     2   14    3
[4,]     2   14    5
[5,]     3   14    2
[6,]     4    7   15
[7,]     4   15   13
[8,]     5    2   14
[9,]     6    3   14
[10,]    7    4   15
[11,]    8   13   15
[12,]    9   15   13
[13,]   10   11    1
[14,]   11    1    2
[15,]   12   10   11
[16,]   13   15    4
[17,]   14    2    5
[18,]   15   13    4
[19,]   15   13    8

I'm trying to get this same information using functions in the spdep package. This is as far I got:

library(spdep)
loc_copy <- loc
coordinates(loc_copy) <- c("x","y")
coords <- coordinates(loc_copy)
n2 <- knn2nb(knearneigh(coords, k=2), row.names=loc$id)
plot(c(-10,10), c(-10, 10), type='n', xlab="x", ylab="y", asp=1)
abline(v=0, col="grey"); abline(h=0,col="grey")
plot(n2, coords, add=TRUE)
text(loc$x, loc$y, cex=0.7, pos=3)

enter image description here

The resulting plot is almost what I want, except some points which shouldn't be connected are connected. For instance, points 11 and 12 shouldn't be connected because we can't go directly from point 11 to 12 or vice versa. I probably didn't create n2 correctly. How do I fix it? And how do I view a neighbours list similar to what I have in the matrix from earlier?

0

There are 0 answers