I ran this if (any())
conditional statement in R
with desired result as follows:
a <- c(1, 4, 6, 3, 2)
b <- 9
d <- 0
if(any(a < b)) d = d 1
d
# 1
I also ran this if (any())
conditional statement in R
with desired result as follows:
a <- c(NA, NA, NA, 3, 2)
b <- 9
d <- 0
if(any(a < b)) d = d 1
d
# 1
But this if (any())
conditional statement in R
runs with error message
as follows:
a <- c(NA, NA, NA, NA, NA)
b <- 9
d <- 0
if(any(a < b)) d = d 1
d
# Error in if (any(a < b)) d = d 1 :
# missing value where TRUE/FALSE needed
The vector of NA
is necessitated as I am running a for loop
and at the first round, the elements of the vector are not present(missing) but will be populated right from the second run.
What I Want
I want a way to do it without the error.
CodePudding user response:
any
has argument na.rm
which you can set as TRUE
to ignore the NA
values.
a <- c(NA, NA, NA, NA, NA)
b <- 9
d <- 0
if(any(a < b, na.rm = TRUE)) d = d 1
d
#[1] 0
CodePudding user response:
Maybe we can have the first expression to check whether all
elements in a
are NA
or not, and in the else if
part, we specify a < b
.
if (all(is.na(a))) d = d else if (any(a < b)) d = d 1
# or better formatted
if (all(is.na(a))) {
d = d
} else if (any(a < b)) {
d = d 1
}