A bit about equality

This commit is contained in:
hadley 2016-03-10 08:49:41 -06:00
parent 64608d305b
commit 3496aafabf
1 changed files with 10 additions and 3 deletions

View File

@ -279,12 +279,19 @@ if (NA) {}
You can use `||` (or) and `&&` (and) to combine multiple logical expressions. These operators are "short-circuiting": as soon as `||` sees the first `TRUE` it returns `TRUE` without computing anything else. As soon as `&&` sees the first `FALSE` it returns `FALSE`. You should never use `|` or `&` in an `if` statement: these are vectorised operations that apply to multiple values. If you do have a logical vector, you can use `any()` or `all()` to collapse it to a single value.
You can enforce this more-strictly by using the `identical()` function, which returns either a single `TRUE` or a single `FALSE`. One thing to watch out for is that *you* have to be more strict when specifying integers:
Be careful when testing for equality. `==` is vectorised, which means that it's easy to get more than one output. Either check the the length is already 1, collapsed with `all()` or `any()`, or use the non-vectorised `identical()`. `identical()` is very strict: it always returns either a single `TRUE` or a single `FALSE`, and doesn't coerce types. This means that you need to be careful when comparing integers and doubles:
```{r}
if (i == 0){}
identical(0L, 0)
```
if (identical(i, 0L)){}
You also need to be wary of floating point numbers:
```{r}
x <- sqrt(2) ^ 2
x
x == 2
x - 2
```
### Multiple conditions