Nearest Neighbors in Spatial Analysis with R

I am interested in doing a diff in diff with census blocks that share a border. I used a nearest neighbour code to get the nearest neighbors but the output is saved an nb list.

How can I incorporate it into my SPDF?

Is there a better way to create pairs of census blocks?

 #> CODE
pacman::p_load(tidycensus)

dfw1 <- blocks(state = 'NJ', county = "Mercer")
plot(dfw1)

  #Identify the tract centroids
            tract_cent <- gCentroid(dfw1, byid=TRUE)
            
            # Neighbors for k = 1
            
            # Find the set of the k nearest neighbors for each tract
            tract_knn1 <- knearneigh(tract_cent, k=1)
           
          
            # Converts the knn object into a neighbors list 
            tract_knb1 <- knn2nb(tract_knn1)
          
            
            # Plot the neighbors
            par(mar=c(0, 0, 0, 0))
            plot(dfw1, border="gray", lwd=4)
            plot(tract_knb1, coords=tract_cent@coords, arrows=TRUE, length=0.08,
                 lwd=2, col="purple", pch=16, cex=0.75, add=TRUE)
            title(main="K Nearest Neighbors\nk = 1", line=-3)

Now I want to create dfw1@data for the each census block in a pair or put a tag in dfw1@data for pairs

Resolved with the following code

library(spdep)
library(rgdal)
library(rgeos)
NY8 <- readOGR(system.file("shapes/NY8_utm18.shp", package="spData"))
NY8_cent <- gCentroid(NY8, byid=TRUE)
NY8_knn <- knearneigh(x=NY8_cent, k=1)
nn_ids <- row.names(NY8)[NY8_knn$nn]
NY8$nn <- nn_ids
 
2 Likes

It might help others to mark this as solved
cheers

1 Like