From 3496aafabf81bbcbff5e0c44d6f07352f0d7f026 Mon Sep 17 00:00:00 2001 From: hadley Date: Thu, 10 Mar 2016 08:49:41 -0600 Subject: [PATCH] A bit about equality --- functions.Rmd | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/functions.Rmd b/functions.Rmd index 2606902..7149f90 100644 --- a/functions.Rmd +++ b/functions.Rmd @@ -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