I have two vectors, let us say:
A <- c(13.25, 14.24, 15.29, 16.27, 17.31)
and
B <- c(10.1, 11.2, 12.1, 13.2, 14.1, 15.3, 16.2, 17.4, 18.3, ...)
and I would like to "match" the values of the first to the second, obtaining the positions of similar values. In this case I would like to obtain
C <- c(4, 5, 6, 7, 8)
I tried with match, but it does not work. Also, I tried match applied to rounded vectors, but the problem is that it does not always work: if B contains 14.48 and C contains 14.51, they are rounded to 14 and 15, respectively...
If you want the nearest value of B
to be matched, then you can use which.min
with the absolute distance from each element of A
:
C <- sapply(A, function(x) which.min(abs(x-B)))
C
[1] 4 5 6 7 8
Updated
With the tolerance, you have to add an extra step to exclude the results out of range:
tolerance <- 0.2
in_range <- unlist(sapply(A, function(x) x[any(abs(x-B) < tolerance)]))
C <- sapply(A, function(x) which.min(abs(x-B)))
C <- C[match(in_range, A)]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments