For example, in Ruby, only nil and false are false. What is what in R?
e.g.: 5==TRUE
and 5==FALSE
both evaluate to FALSE. However, 1==TRUE
is TRUE
. Is there any general rule as to what (objects, numbers, etc.) evaluate to?
TRUE and FALSE are reserved words denoting logical constants in the R language, whereas T and F are global variables whose initial values set to these. All four are logical(1) vectors.
R – all() function all() function in R Language will check in a vector whether all the values are true or not.
Check whether a value is logical or not in R Programming – is. logical() Function. is. logical() function in R Language is used to check whether a value is logical or not.
In R, true values are designated with TRUE, and false values with FALSE. When you index a vector with a logical vector, R will return values of the vector for which the indexing vector is TRUE.
This is documented on ?logical
. The pertinent section of which is:
Details: ‘TRUE’ and ‘FALSE’ are reserved words denoting logical constants in the R language, whereas ‘T’ and ‘F’ are global variables whose initial values set to these. All four are ‘logical(1)’ vectors. Logical vectors are coerced to integer vectors in contexts where a numerical value is required, with ‘TRUE’ being mapped to ‘1L’, ‘FALSE’ to ‘0L’ and ‘NA’ to ‘NA_integer_’.
The second paragraph there explains the behaviour you are seeing, namely 5 == 1L
and 5 == 0L
respectively, which should both return FALSE
, where as 1 == 1L
and 0 == 0L
should be TRUE for 1 == TRUE
and 0 == FALSE
respectively. I believe these are not testing what you want them to test; the comparison is on the basis of the numerical representation of TRUE
and FALSE
in R, i.e. what numeric values they take when coerced to numeric.
However, only TRUE
is guaranteed to the be TRUE
:
> isTRUE(TRUE) [1] TRUE > isTRUE(1) [1] FALSE > isTRUE(T) [1] TRUE > T <- 2 > isTRUE(T) [1] FALSE
isTRUE
is a wrapper for identical(x, TRUE)
, and from ?isTRUE
we note:
Details: .... ‘isTRUE(x)’ is an abbreviation of ‘identical(TRUE, x)’, and so is true if and only if ‘x’ is a length-one logical vector whose only element is ‘TRUE’ and which has no attributes (not even names).
So by the same virtue, only FALSE
is guaranteed to be exactly equal to FALSE
.
> identical(F, FALSE) [1] TRUE > identical(0, FALSE) [1] FALSE > F <- "hello" > identical(F, FALSE) [1] FALSE
If this concerns you, always use isTRUE()
or identical(x, FALSE)
to check for equivalence with TRUE
and FALSE
respectively. ==
is not doing what you think it is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With