我想找出向量中三个最接近的数字。就像是
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)
r ×1