BarneyC
BarneyC

Reputation: 529

R %in% doesn't work for values greater than -0.999

Today I came across an oddity with base I can't find an explanation for.

I have an interval (-0.031,0.105) and I wanted to test if 0 (zero) was in this. Simple, but...

> 0 %in% -0.031:0.105
[1] FALSE

A quick play shows that R can happily do this for values less than -1 though.

> 0 %in% -1.0:0.105
[1] TRUE

Can anyone shed light on why this doesn't work as expected and how to resolve?

Upvotes: 0

Views: 62

Answers (1)

takje
takje

Reputation: 2800

The %in% operator

The %in% operator looks for a value in a vector and returns TRUE if he found the value (at least once). Some examples:

0 %in% c(-1,0,1)
> TRUE # zero is in the vector
0 %in% c(-0.5,0.5)
> FALSE # zero is not in the vector
'Anna' %in% c('Anna','Bob')
> TRUE # it also works for characters

The : operator

The : operator is short for seq(from,to). One of the default values of seq() is the step which is 1 by default. Therefore this would be the output of your code:

-0.031:0.105
> [1] -0.031 # (to is less than 1 higher than from)
-1.0:0.105
> [1] -1  0 # (here he can actually add a second number which is the 0)

As you can see this is not exactly the behavior that you want to achieve. There is however a function that does this:

The between function

Bot dplyr and data.table provide functions to create this behavior: dplyr::between(value, lower, upper) or data.table::between(value, lower, upper). The data.table %between% operator is based upon the data.table::between() function. Therefore, in your case you could do:

between(0,-0.031,0.105)
> TRUE

which would correctly return TRUE.

Upvotes: 3

Related Questions