Check if element exists in vector R

不问归期 提交于 2019-12-12 22:47:49

问题


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


来源:https://stackoverflow.com/questions/40527925/check-if-element-exists-in-vector-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!