Martin Schmelzer Martin Schmelzer - 1 year ago 78
R Question

is.element() doesn't check correctly (?) in R

I got a little weird problem here:

setProgress <- function(total) {
ticks <- seq(.01, 1, by = 0.01) * total
return(ticks)
}

ticks <- setProgress(10000)
is.element(100, ticks)
is.element(205, ticks)
# ...
is.element(700, ticks)


If you run that code you will get:

Clearly 100 is part of the vector
ticks
. ->
TRUE


205 is obviously not. ->
FALSE


700 is part of
ticks
but I receive the output
FALSE
.

What is going on here?

Cheers,
Martin

Answer Source

It's a rounding error. Set options(digits=22) and view ticks. You'll find this value: 7000.0000000000009094947

The error is because 0.7 cannot be exactly represented as a binary floating point number.

You may be able to fix it by using this definition:

 setProgress <- function(total) { seq(total/100, total, length=100) }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download