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:

Step 1. Convert your matrix of values into a arrayvec object
library(kdtools)
x = matrix(runif(3e3), nc = 3)
y = matrix_to_tuples(x)
y[1:3, c(1, 3)]
#>            [,1]      [,2]
#> [1,] 0.25834951 0.4861129
#> [2,] 0.03034524 0.5649745
#> [3,] 0.42606723 0.1469675

The arrayvec object can be manipulated as if it were a matrix.

Step 2. Sort the data
kd_sort(y, inplace = TRUE, parallel = TRUE)
#>            [,1]       [,2]       [,3]
#> [1,] 0.07977239 0.11978295 0.10041752
#> [2,] 0.05642256 0.09828960 0.19815089
#> [3,] 0.09291032 0.07148259 0.20112564
#> [4,] 0.07616577 0.12835161 0.07973155
#> [5,] 0.10496537 0.16711053 0.07296113
#> (continues for 995 more rows)
Step 3. Search the data
rq = kd_range_query(y, c(0, 0, 0), c(1/4, 1/4, 1/4)); rq
#>            [,1]       [,2]       [,3]
#> [1,] 0.07977239 0.11978295 0.10041752
#> [2,] 0.05642256 0.09828960 0.19815089
#> [3,] 0.09291032 0.07148259 0.20112564
#> [4,] 0.07616577 0.12835161 0.07973155
#> [5,] 0.10496537 0.16711053 0.07296113
#> (continues for 15 more rows)
i = kd_nearest_neighbor(y, c(0, 0, 0)); y[i, ]
#> [1] 0.07616577 0.12835161 0.07973155
nns = kd_nearest_neighbors(y, c(0, 0, 0), 100); nns
#>            [,1]      [,2]      [,3]
#> [1,] 0.01060028 0.4445945 0.3598633
#> [2,] 0.35399148 0.3678210 0.2560636
#> [3,] 0.43505101 0.2829680 0.2341742
#> [4,] 0.24791701 0.3908070 0.3296455
#> [5,] 0.35757756 0.3348116 0.2877254
#> (continues for 95 more rows)
nni = kd_nn_indices(y, c(0, 0, 0), 10); nni
#>  [1] 64 17  3  9  2  6  5  7  1  4

The kd_nearest_neighbor and kd_nn_indices functions return row-indices. The other functions return arrayvec objects.

Step 4. Convert back to a matrix for use in R
head(tuples_to_matrix(rq))
#>            [,1]       [,2]       [,3]
#> [1,] 0.07977239 0.11978295 0.10041752
#> [2,] 0.05642256 0.09828960 0.19815089
#> [3,] 0.09291032 0.07148259 0.20112564
#> [4,] 0.07616577 0.12835161 0.07973155
#> [5,] 0.10496537 0.16711053 0.07296113
#> [6,] 0.08924499 0.17761309 0.08829078
head(tuples_to_matrix(nns))
#>            [,1]       [,2]      [,3]
#> [1,] 0.01060028 0.44459446 0.3598633
#> [2,] 0.35399148 0.36782096 0.2560636
#> [3,] 0.43505101 0.28296796 0.2341742
#> [4,] 0.24791701 0.39080698 0.3296455
#> [5,] 0.35757756 0.33481162 0.2877254
#> [6,] 0.42247297 0.08266129 0.3699597

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.