NorthNW
NorthNW

Reputation: 167

How to filter out each polygon from its list of neighbors with sf::st_intersects

I need to extract the neighboring polygons for each polygon in an sf dataset.

Here's a quick example:

library(tidyverse)
library(sf)

demo(nc, ask = FALSE, verbose = FALSE)
nc <- nc %>% 
  mutate(polygon_id = row_number())

I have managed to extract the neighbors with sf::st_intersects

neighbors <- st_intersects(nc, nc)
neighbors[[5]]
[1]  5  6  9 16 28

The issue is that each polygon (here, 5) is being included in the list of neighbors. Using only one nc dataset gives me the same result

neighbors <- st_intersects(nc)
neighbors[[5]]
[1]  5  6  9 16 28

Any tips on how to filter out the actual polygon from the list of adjacent/neighboring polygons?

Upvotes: 2

Views: 791

Answers (1)

Gray
Gray

Reputation: 1388

Good question. This question could have many solutions. But the simple answer for this question: "Any tips on how to filter out the actual polygon from the list of adjacent/neighboring polygons?", was accomplished using the Jupyter Lab IDE with the R kernel. The following code provides one way to answer the question.

There are 100 counties in the nc dataset. This code displays the selected county in color and shows all the neighboring counties. This code works for any of the 100 counties in nc. The county 100 was selected here.

Code:

nc1 <- nc %>% mutate(c_id = 1:nrow(nc))        
n = 100                  
grp <- st_intersects(nc1, nc1[n,1]   , sparse = F ) 

neighborhood <- nc1[grp,]
neighborhood 

plot(neighborhood$geom)
plot(nc1[n,1], col = 'blue', add = TRUE)   #

This code is easily extended. I wrote a quick little function that displays the names of the neighboring countries (not shown here), but this question seems to be most likely a plotting related question.

The plot is shown at Link

Upvotes: 1

Related Questions