Skip to content

which.min, equal values and fractions

2 messages · Mike, Ivan Krylov

#
Hi,

According to ?which.min it returns the "index of the (first)
minimum". So I would expect it to also return the first minimum when
providing two identical extrema. But my minimal reproducible doesn't
do so:

data1a <- c(3.2,4.2)
data1b <- c(3.1,4.1)

data2a <- c(0.2,1.2)
data2b <- c(4.2,5.2)

data3aa <- data1a - data2a
data3ba <- data1b - data2a
data3ab <- data1a - data2b
data3bb <- data1b - data2b

print (data3aa)
print (which.min (data3aa))
print (which.max (data3aa))

print (data3ba)
print (which.min (data3ba))
print (which.max (data3ba))

print (data3ab)
print (which.min (data3ab))
print (which.max (data3ab))

print (data3bb)
print (which.min (data3bb))
print (which.max (data3bb))

results in:

[1] 3 3
[1] 1
[1] 1
[1] 2.9 2.9
[1] 2
[1] 1
[1] -1 -1
[1] 1
[1] 1
[1] -1.1 -1.1
[1] 2
[1] 1

First of all which.max works as expected by always returning 1.

But which.min only does so if the values don't contain fractions.
And I get
[1] FALSE

Why is which.min not always returning 1 but which.max does?

Mike
#
On Tue, 25 Aug 2020 14:26:43 +0200
Mike <mike9 at posteo.nl> wrote:

            
It's the unfortunate consequence of the way floating point numbers
work:

data3ba - 2.9
# [1]  0.000000e+00 -4.440892e-16

See R FAQ 7.31:
https://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-doesn_0027t-R-think-these-numbers-are-equal_003f