which-query won't work

I have the vector appx and want to find the place in the vector where the value is 33.05. The which-query works for every other number in the vector but not for 33.05. I have no idea why it is not working.
I hope someone can help me, thanks.

This is the problem with numerical accuracy and/or with printing. Here is an example of what I mean:

x <- c(0.35, 0.3499999999999999)
x
#> [1] 0.35 0.35

which(x == 0.35)
#> [1] 1

Created on 2018-11-23 by the reprex package (v0.2.1)
As you can see, second number is printed as 0.35, but which can't find it.

In general, when you are dealing with floats, exact comparisons are impossible, so it's better to use something like all.equal that takes into account numerical precision.

1 Like

Thank's a lot.
But how can I combine all.equal with my which-query?

You can use purrr::map_lgl/sapply/vapply. I've used map:

xs <- c(0.35, 0.3499999999999999, 0.36)

y <- 0.35
indices <- purrr::map_lgl(xs, ~isTRUE(all.equal(.x, y)))
which(indices == TRUE)
#> [1] 1 2

y <- 0.36
indices <- purrr::map_lgl(xs, ~isTRUE(all.equal(.x, y)))
which(indices == TRUE)
#> [1] 3

Created on 2018-11-23 by the reprex package (v0.2.1)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.