Finds which points sit in a box, or near another point.
Details
write() saves the index to a file and KDTree$read() opens it again, so
you build it once and reuse it across sessions. With mmap = TRUE,
read() maps the file instead of reading it, so the index opens at once
and each query loads only the parts of the tree it visits.
Methods
Method read
Read an index that write() saved
Arguments
paththe file
write()savedmmapwhether to map the file rather than read it into memory
Method write
Save the index to a file
details
write() saves the tree with the row each point came from, so
KDTree$read() restores an index that answers every query the same
way. The tree keeps the layout of the JavaScript kdbush library.
Examples
fp <- system.file("shape/nc.shp", package = "sf")
nc <- as.data.frame(read_shapefile(fp))
pts <- ga_centroid(nc$geometry)
idx <- KDTree$new(pts)
# every centroid within half a degree of every other
head(as.vector(idx$within(pts, 0.5)), 3)
#> <list_of<double>[3]>
#> [[1]]
#> [1] 1 2 18 19 34
#>
#> [[2]]
#> [1] 1 2 3 18
#>
#> [[3]]
#> [1] 2 3 10 23
#>
# for a single lookup, pass an array of one
as.vector(idx$within(ga_point(-78.6, 35.8), 0.5))[[1]]
#> [1] 24 30 37 54
# save the index and open it again without reading the whole file
path <- tempfile(fileext = ".gaix")
idx$write(path)
#> NULL
saved <- KDTree$read(path, mmap = TRUE)
as.vector(saved$within(ga_point(-78.6, 35.8), 0.5))[[1]]
#> [1] 24 30 37 54