获得数值向量的最小差

时间:2018-06-21 05:55:09

标签: r

如何获取R中数字向量中两个数字之间的最小差。例如:

foo<- c(1,2,2.5,3,4)

上述向量的最小差为0.5(2.5-2)。

当前,我使用以下代码实现我的目标:

> sapply(1:length(foo), function (x)(foo[-x] - foo[x]))
     [,1] [,2] [,3] [,4] [,5]
[1,]  1.0 -1.0 -1.5 -2.0 -3.0
[2,]  1.5  0.5 -0.5 -1.0 -2.0
[3,]  2.0  1.0  0.5 -0.5 -1.5
[4,]  3.0  2.0  1.5  1.0 -1.0
> min(abs(sapply(1:length(foo), function (x)(foo[-x] - foo[x]))))
[1] 0.5

是否有任何可用的软件包可以通过单个命令执行相同的操作,或者是否有更有效的方法来执行此操作?

2 个答案:

答案 0 :(得分:3)

您可以尝试使用此功能:

foo<- c(1,2,2.5,4,3)
min(diff(sort(foo)), na.rm=TRUE) #sort the data in ascending order then take the differences

答案 1 :(得分:2)

您可以使用min中的diffdiff提供了连续元素之间的区别,默认参数为lag=1。然后,最后取min的相同值。

min(diff(foo))
#[1] 0.5