Our
Our

Reputation: 1035

Find the minimum distance to a set

I have two sets, A and B, both containing positions of some particles. What I want to do is the following:

For each element a in A, 
    Calculate the minimum distance between a and the elements of B.
Put these distances in to a list and return.

I know how to do this with looks, but I don't know how to do it in a fast way using data.table syntax.

Upvotes: 2

Views: 201

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 102625

Another base R option using expand.grid + aggregate

aggregate(cbind(d = abs(A - B)) ~ A, expand.grid(A = A, B = B), min)

gives

> aggregate(cbind(d = abs(A - B)) ~ A, expand.grid(A = A, B = B), min)
          A           d
1 0.2016819 0.004292644
2 0.2655087 0.059534088
3 0.3721239 0.011979819
4 0.5728534 0.056260681
5 0.9082078 0.009818105

Data

set.seed(1)
A <- runif(5)
B <- runif(10)

Upvotes: 0

akrun
akrun

Reputation: 887831

We can use sapply to loop over 'A', get the min absolute difference from the 'B' vector and store as a vector

sapply(A, function(x) min(abs(x - B)))

Or with data.table syntax

dt1[, lapply(A, function(x) min(abs(x - B)))]

If the vectors are sorted, a fast option is findInterval

A[findInterval(A, B)]

If these are columns of data.table

dt1[, A[findInterval(A, B)]]

Or using outer

outer(A, B, FUN = function(x, y) min(abs(x - y)))

Upvotes: 4

Related Questions