TRUE / FALSE result in R
I have the following vectors:
A <- c(8.4, 9.5, 8.1)
B <- c(NA,NA,NA)
I wanted R to do the following: if column A has values less than 8.5 or column B values less than 8 for the record "TRUE", otherwise write "FALSE".
I tried the following:
C <- (A <8.5 | B <8)
I was expecting the following: TRUE, FALSE, TRUE
But the result was:
> C
# [1] TRUE NA TRUE
Obviously, when R saw that A was at least 8.5 in the second variable, she went to B, and when there was NA, she wrote NA as the result.
Do you have any suggestions on how I can avoid this?
Use isTRUE
:
isTRUE( FALSE | NA)
[1] FALSE
It is unwise to use "C" as a variable name, since "c" and "C" are (different) R functions. But with your example:
> sapply(C, isTRUE)
[1] TRUE FALSE TRUE
You can use a function is.na
to first determine if B is NA
, if it is set, you can check if it is less.
C <-(A < 8.5 | (!is.na(B) & B < 8) )