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.5985533 0.02735486
#> [2,] 0.2443595 0.92998987
#> [3,] 0.7264726 0.14657568
The arrayvec object can be manipulated as if it were a matrix.
kd_sort(y, inplace = TRUE, parallel = TRUE)
#> [,1] [,2] [,3]
#> [1,] 0.065346144 0.08435270 0.133891112
#> [2,] 0.046677350 0.02532216 0.137350342
#> [3,] 0.008501512 0.12522006 0.239608221
#> [4,] 0.046071197 0.13077596 0.008139925
#> [5,] 0.084342897 0.15383111 0.080081249
#> (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.065346144 0.08435270 0.133891112
#> [2,] 0.046677350 0.02532216 0.137350342
#> [3,] 0.008501512 0.12522006 0.239608221
#> [4,] 0.046071197 0.13077596 0.008139925
#> [5,] 0.084342897 0.15383111 0.080081249
#> (continues for 10 more rows)
i = kd_nearest_neighbor(y, c(0, 0, 0)); y[i, ]
#> [1] 0.046071197 0.130775964 0.008139925
nns = kd_nearest_neighbors(y, c(0, 0, 0), 100); nns
#> [,1] [,2] [,3]
#> [1,] 0.1277692 0.437569526 0.32168002
#> [2,] 0.2793376 0.388687962 0.28494865
#> [3,] 0.3005189 0.004624579 0.46646528
#> [4,] 0.3187083 0.443614474 0.08065064
#> [5,] 0.1694558 0.286615866 0.43909069
#> (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.065346144 0.08435270 0.133891112
#> [2,] 0.046677350 0.02532216 0.137350342
#> [3,] 0.008501512 0.12522006 0.239608221
#> [4,] 0.046071197 0.13077596 0.008139925
#> [5,] 0.084342897 0.15383111 0.080081249
#> [6,] 0.036141004 0.15108840 0.141544112
head(tuples_to_matrix(nns))
#> [,1] [,2] [,3]
#> [1,] 0.1277692 0.437569526 0.32168002
#> [2,] 0.2793376 0.388687962 0.28494865
#> [3,] 0.3005189 0.004624579 0.46646528
#> [4,] 0.3187083 0.443614474 0.08065064
#> [5,] 0.1694558 0.286615866 0.43909069
#> [6,] 0.3991862 0.172503423 0.33556040
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.