which.min, equal values and fractions

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

which.min, equal values and fractions

Mike-3
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

> identical (data3ba, c(2.9,2.9))
[1] FALSE

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

Mike

______________________________________________
[hidden email] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: which.min, equal values and fractions

Ivan Krylov
On Tue, 25 Aug 2020 14:26:43 +0200
Mike <[hidden email]> wrote:

> But which.min only does so if the values don't contain fractions.
> And I get
>
> > identical (data3ba, c(2.9,2.9))  
> [1] FALSE
>
> Why is which.min not always returning 1 but which.max does?

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

--
Best regards,
Ivan

______________________________________________
[hidden email] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.