The kdtools package can be used to search for multidimensional points in a boxed region and find nearest neighbors in 1 to 9 dimensions. The package uses binary search on a sorted sequence of values. The current package is limited to matrices of real values. If you are interested in using string or mixed types in different dimensions, see the methods vignette.
Using kdtools is straightforward. There are four steps:
library(kdtools)
x = matrix(runif(3e3), nc = 3)
y = matrix_to_tuples(x)
y[1:3, c(1, 3)]
#> [,1] [,2]
#> [1,] 0.16703884 0.25734339
#> [2,] 0.94165585 0.05545947
#> [3,] 0.04914331 0.03548422
The arrayvec object can be manipulated as if it were a matrix.
kd_sort(y, inplace = TRUE, parallel = TRUE)
#> [,1] [,2] [,3]
#> [1,] 0.06884210 0.1274742 0.05930235
#> [2,] 0.01041528 0.0653356 0.19152889
#> [3,] 0.01596592 0.1180759 0.22342213
#> [4,] 0.10676432 0.1460012 0.16355226
#> [5,] 0.01094750 0.1969294 0.14268431
#> (continues for 995 more rows)
rq = kd_range_query(y, c(0, 0, 0), c(1/4, 1/4, 1/4)); rq
#> [,1] [,2] [,3]
#> [1,] 0.06884210 0.1274742 0.05930235
#> [2,] 0.01041528 0.0653356 0.19152889
#> [3,] 0.01596592 0.1180759 0.22342213
#> [4,] 0.10676432 0.1460012 0.16355226
#> [5,] 0.01094750 0.1969294 0.14268431
#> (continues for 10 more rows)
i = kd_nearest_neighbor(y, c(0, 0, 0)); y[i, ]
#> [1] 0.06884210 0.12747424 0.05930235
nns = kd_nearest_neighbors(y, c(0, 0, 0), 100); nns
#> [,1] [,2] [,3]
#> [1,] 0.1902136 0.08018343 0.5332578
#> [2,] 0.2163445 0.18600993 0.4911272
#> [3,] 0.1793220 0.10475322 0.5285435
#> [4,] 0.5318303 0.14216661 0.1370179
#> [5,] 0.4537643 0.09302618 0.3263729
#> (continues for 95 more rows)
The kd_nearest_neighbor
function returns the row-index of the nearest neighbor. The other functions return arrayvec objects.
head(tuples_to_matrix(rq))
#> [,1] [,2] [,3]
#> [1,] 0.06884210 0.1274742 0.05930235
#> [2,] 0.01041528 0.0653356 0.19152889
#> [3,] 0.01596592 0.1180759 0.22342213
#> [4,] 0.10676432 0.1460012 0.16355226
#> [5,] 0.01094750 0.1969294 0.14268431
#> [6,] 0.07211760 0.1925596 0.21318300
head(tuples_to_matrix(nns))
#> [,1] [,2] [,3]
#> [1,] 0.19021361 0.08018343 0.5332578
#> [2,] 0.21634452 0.18600993 0.4911272
#> [3,] 0.17932205 0.10475322 0.5285435
#> [4,] 0.53183025 0.14216661 0.1370179
#> [5,] 0.45376430 0.09302618 0.3263729
#> [6,] 0.01099928 0.31020067 0.4734836
If you pass a matrix instead of an arrayvec object to any of the functions, it will be converted to an arrayvec object internally and results will be returned as matrices. This is slower and provided for convenience.