I need a sort function that treats numbers that would be equal using all.equal()
as if they are equal.
For instance, if you do:
library(plyr)
a = sample(c(0.8, 0.7), 30, replace=TRUE)
b = sample(c(1.1, 1.2), 30, replace=TRUE)
df = data.frame(a)
df$b = b
df$sum = a + b
arrange(df, desc(sum))
All pairs of (0.8, 1.1) will sort above pairs of (0.7, 1.2), which is not what I want--I want the random order to be preserved within the category of things that sum to 1.9.
This is happening because
> 1.1 + 0.8 > 1.2 + 0.7
[1] TRUE
and
> 1.1 + 0.8 == 1.2 + 0.7
[1] FALSE
I understand that this is a consequence of how floating point numbers work, and that R has a function all.equal()
to test for "true" equality. For example
> all.equal(0.8+1.1, 0.7+1.2)
[1] TRUE
So I'm looking for a sort function or a way to sort that behaves as all.equal()
does and not as ==
does.
Edited to make clear this is not a duplicate of other questions.