我有两个集合,A和B,都包含一些粒子的位置。我想做的是:
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.
我知道如何使用外观来实现这一点,但我不知道如何使用data.table
语法快速实现。
我们可以使用sapply
在"A"上循环,从"B"向量获得min
abs
解差,并存储为vector
sapply(A, function(x) min(abs(x - B)))
或者使用data.table
语法
dt1[, lapply(A, function(x) min(abs(x - B)))]
如果对矢量进行排序,则快速选项为findInterval
A[findInterval(A, B)]
如果这些是data.table
的列
dt1[, A[findInterval(A, B)]]
或使用outer
outer(A, B, FUN = function(x, y) min(abs(x - y)))
使用expand.grid
+aggregate
的另一个基本R选项
aggregate(cbind(d = abs(A - B)) ~ A, expand.grid(A = A, B = B), min)
给出
> 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
数据
set.seed(1)
A <- runif(5)
B <- runif(10)