S.Br
S.Br

Reputation: 33

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.

Upvotes: 1

Views: 61

Answers (2)

Sotos
Sotos

Reputation: 51582

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

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 388797

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

Upvotes: 5

Related Questions