I would like to use the tmap
library to display my nearest neighbour analysis above. My code is below with a simple plot function to create the map attached but like I said i want to display this using tmap
#Identify the tract centroids
tract_cent <- gCentroid(dfw1, byid=TRUE)
tract_centspdf<- SpatialPointsDataFrame(gCentroid(dfw1, byid=TRUE), dfw1@data, match.ID=FALSE)
# Neighbors for k = 1
# Find the set of the k nearest neighbors for each tract
tract_knn1 <- knearneigh(tract_centspdf, k=1)
#create a column with index number
dfw1@data <- dfw1@data %>% mutate(id = row_number())
# add IDs to spdf data frame
dfw1$nn= tract_knn1$nn
summary(dfw1$nn)
# 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)
#TMAP code
tm_shape(dfw1) +
tm_polygons("Consumer", title="Fiber Optic availability") +
tm_shape(centroids)+
tm_dots()
tm_shape(tract_knb1, tract_centspdf)+
tm_markers(arrows=TRUE, length=0.08,
lwd=2, col="purple", pch=16, cex=0.75, add=TRUE)
tm_style_white()
Error in rep(no, length.out = length(ans)) : attempt to replicate an object of type 'S4'