1

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.

Sotos
  • 51,121
  • 6
  • 32
  • 66
S.Br
  • 33
  • 4

2 Answers2

5

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
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
2

Another idea is to use expand.grid, i.e.

df1 <- transform(expand.grid(A, B), var3 = abs(Var1 - Var2))

min_diff_value <- min(df1$var3)
#[1] 0.1
min_value_A <- df1$Var1[which.min(df1$var3)]
#[1] 4
min_value_B <- df1$Var2[which.min(df1$var3)]
#[1] 3.9
Sotos
  • 51,121
  • 6
  • 32
  • 66