I have two arrays "F1" and "F2":
F1 <- c(1,3,4,5)
F2 <- c(6,7,8,9)
I want to find nearest neighbor of each element in both "F1" and "F2".
Example: for value 3 in "F1", the nearest neighbor in "F1" is 4. And the nearest neighbor of 1 in "F2" is 6. And for value 9 in "F2", the nearest neighbor is 8, and 5 in "F1".
you could use the RANN
package:
F1 <- c(1,3,4,5)
F2 <- c(6,7,8,9)
require(RANN)
nn2(F1,F2,k = 1)
which should produce the following results:
> nn2(F1,F2,k = 1)
$nn.idx
[,1]
[1,] 4
[2,] 4
[3,] 4
[4,] 4
$nn.dists
[,1]
[1,] 1
[2,] 2
[3,] 3
[4,] 4
Naturally, you may consider modifying the nn2
syntax to get more desirable results. The method uses the ANN library which gives you a lot of opportunities on how to find your nearest neighbours.
I'm thinking that you may be actually interested in finding the closest match . For example to find the closest match for the number 6
you could do:
which(abs(F1-6)==min(abs(F1-6)))
This is not the same as identifying the nearest neighbours.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.