小编Ter*_*rry的帖子

如何找到向量中三个最接近的(最近的)值?

我想找出向量中三个最接近的数字。就像是

v = c(10,23,25,26,38,50)
c = findClosest(v,3)
c
23 25 26
Run Code Online (Sandbox Code Playgroud)

我尝试使用sort(colSums(as.matrix(dist(x))))[1:3],并且效果不错,但是它选择了具有最小整体距离的三个数字,而不是三个最接近的数字。

matlab已经有一个答案,但是我不知道如何将其转换为R:

%finds the index with the minimal difference in A
minDiffInd = find(abs(diff(A))==min(abs(diff(A))));
%extract this index, and it's neighbor index from A
val1 = A(minDiffInd);
val2 = A(minDiffInd+1);
Run Code Online (Sandbox Code Playgroud)

如何在MATLAB中的向量中找到两个最接近的(最近的)值?

r

14
推荐指数
4
解决办法
652
查看次数

标签 统计

r ×1