# NOT RUN {
columbus <- st_read(system.file("shapes/columbus.shp", package="spData")[1], quiet=TRUE)
coords <- st_centroid(st_geometry(columbus), of_largest_polygon=TRUE)
rn <- row.names(columbus)
k1 <- knn2nb(knearneigh(coords))
all.linked <- max(unlist(nbdists(k1, coords)))
col.nb.0.all <- dnearneigh(coords, 0, all.linked, row.names=rn)
summary(col.nb.0.all, coords)
opar <- par(no.readonly=TRUE)
plot(st_geometry(columbus), border="grey", reset=FALSE,
main=paste("Distance based neighbours 0-", format(all.linked), sep=""))
plot(col.nb.0.all, coords, add=TRUE)
par(opar)
(sfc_obj <- st_centroid(st_geometry(columbus)))
col.nb.0.all_sf <- dnearneigh(sfc_obj, 0, all.linked, row.names=rn)
all.equal(col.nb.0.all, col.nb.0.all_sf, check.attributes=FALSE)
data(state)
us48.fipsno <- read.geoda(system.file("etc/weights/us48.txt",
package="spdep")[1])
if (as.numeric(paste(version$major, version$minor, sep="")) < 19) {
m50.48 <- match(us48.fipsno$"State.name", state.name)
} else {
m50.48 <- match(us48.fipsno$"State_name", state.name)
}
xy <- as.matrix(as.data.frame(state.center))[m50.48,]
llk1 <- knn2nb(knearneigh(xy, k=1, longlat=FALSE))
(all.linked <- max(unlist(nbdists(llk1, xy, longlat=FALSE))))
ll.nb <- dnearneigh(xy, 0, all.linked, longlat=FALSE)
summary(ll.nb, xy, longlat=TRUE, scale=0.5)
gck1 <- knn2nb(knearneigh(xy, k=1, longlat=TRUE))
(all.linked <- max(unlist(nbdists(gck1, xy, longlat=TRUE))))
gc.nb <- dnearneigh(xy, 0, all.linked, longlat=TRUE)
summary(gc.nb, xy, longlat=TRUE, scale=0.5)
plot(ll.nb, xy)
plot(diffnb(ll.nb, gc.nb), xy, add=TRUE, col="red", lty=2)
title(main="Differences Euclidean/Great Circle")
xy1 <- SpatialPoints((as.data.frame(state.center))[m50.48,],
proj4string=CRS("+proj=longlat +ellps=GRS80"))
gck1a <- knn2nb(knearneigh(xy1, k=1))
(all.linked <- max(unlist(nbdists(gck1a, xy1))))
gc.nb <- dnearneigh(xy1, 0, all.linked)
summary(gc.nb, xy1, scale=0.5)
xy1 <- st_as_sf((as.data.frame(state.center))[m50.48,], coords=1:2,
crs=st_crs("+proj=longlat +ellps=GRS80"))
old_use_s2 <- sf_use_s2()
sf_use_s2(TRUE)
gck1b <- knn2nb(knearneigh(xy1, k=1))
system.time(o <- nbdists(gck1b, xy1))
(all.linked <- max(unlist(o)))
# use s2 brute-force buffer/intersect approach (with two passes if d1 > 0)
system.time(gc.nb <- dnearneigh(xy1, 0, all.linked, use_s2=TRUE))
summary(gc.nb, xy1, scale=0.5)
# use s2 brute-force buffer/intersect approach with smaller max_cells
system.time(gc.nb <- dnearneigh(xy1, 0, all.linked, use_s2=TRUE, max_cells=500))
summary(gc.nb, xy1, scale=0.5)
# use s2 brute-force dwithin_matrix approach
system.time(gc.nb <- dnearneigh(xy1, 0, all.linked, use_s2=TRUE, dwithin=TRUE))
summary(gc.nb, xy1, scale=0.5)
# use legacy symmetric brute-force approach
system.time(gc.nb <- dnearneigh(xy1, 0, all.linked))
summary(gc.nb, xy1, scale=0.5)
sf_use_s2(old_use_s2)
# }
Run the code above in your browser using DataLab