Check if element exists in vector R

2019-08-04 02:03发布

问题:

I am fighting with some weird behavior of R. Can someone explain what is happening?

In the following example, check is false in the first example, and true in the second one. Why is seq different to c?

by <- 0.1
percentage <- 60

probs <- seq(0,1,by)
checkValues <- probs * 100
check <- percentage %in% checkValues

probs <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
checkValues <- probs * 100
check <- percentage %in% checkValues

It is getting even weirder, as if I set by <- 0.25 and percentage <- 75 both check are true

回答1:

You've fallen victim to floating point error:

p1 <- seq(0,1,0.1)
p2 <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
> identical(p1, p2)
[1] FALSE
> all.equal(p1, p2)
[1] TRUE


标签: r seq