R Tip: use isTRUE()
.
A lot of R functions are type unstable, which means they return different types or classes depending on details of their values.
For example consider all.equal()
, it returns the logical value TRUE
when the items being compared are equal:
However, when the items being compared are not equal all.equal()
instead returns a message:
This can be inconvenient in using functions similar to all.equal()
as tests in if()
-statements and other program control structures.
The saving functions is isTRUE()
. isTRUE()
returns TRUE
if its argument value is equivalent to TRUE
, and returns FALSE
otherwise. isTRUE()
makes R
programming much easier.
Some examples of isTRUE()
are given below:
Using isTRUE()
one can write safe and legible code such as the following:
R
now also has isFALSE()
, but by design it does not mean the same thing as !isTRUE()
. The ideas is: for a value v
at most of one of isTRUE()
or isFALSE()
is set, and both are non-NA unnamed scalar logical values. (example: isTRUE(5)
, isFALSE(5)
).
Or as help(isTRUE)
puts it:
… if(isTRUE(cond)) may be preferable to if(cond) …
Note: prior to R
3.5 isTRUE
(the current version!) was defined as “isTRUE <- function(x) identical(x, TRUE)
” (please see change-log here). This seemed clever, but failed on named logical values (violating a principle of least surprise):
This caused a lot of problems (example taken from R3.5.0 NEWS):
Like this:
Like Loading…
Related