Search code examples
rvectordifferenceminimumelementwise-operations

What the best way to find minimal difference and corresponding value with element-wise vector comparison?


I have one problem.
Vector A is the query, Vector B is the ref.
I want to see which value of A is the closest to one of the B value.
Both vectors are ordered.

INPUT

A = c(1, 1.2, 4, 8, 9, 10, 30)
B = c(0.1, 3.9)

OUTPUT

min_diff_value = 0.1
min_value_A = 4
min_value_B = 3.9 (optionnal)

I want to know if there may be a trick to perform this without time-consuming loop?
Thank you.


Solution

  • You could use outer

    A = c(1, 1.2, 4, 8, 9, 10, 30)
    B = c(0.1, 3.9)
    
    mat <- outer(A, B, `-`)
    min_diff_value <- min(abs(mat))
    dim <- which(mat == min_diff_value, arr.ind = TRUE)
    min_value_A <- A[dim[, 1]]
    min_value_B <- B[dim[, 2]]
    
    min_diff_value
    #[1] 0.1
    min_value_A
    #[1] 4
    min_value_B
    #[1] 3.9