How to include NA in ifelse? How to include NA in ifelse? r r

How to include NA in ifelse?


You can't really compare NA with another value, so using == would not work. Consider the following:

NA == NA# [1] NA

You can just change your comparison from == to %in%:

ifelse(is.na(test$time) | test$type %in% "A", NA, "1")# [1] NA  "1" NA  "1"

Regarding your other question,

I could get this to work with my existing code if I could somehow change the result of is.na(test$type) to return FALSE instead of TRUE, but I'm not sure how to do that.

just use ! to negate the results:

!is.na(test$time)# [1]  TRUE  TRUE FALSE  TRUE


It sounds like you want the ifelse statement to interpret NA values as FALSE instead of NA in the comparison. I use the following functions to handle this situation so I don't have to continuously handle the NA situation:

falseifNA <- function(x){  ifelse(is.na(x), FALSE, x)}ifelse2 <- function(x, a, b){  ifelse(falseifNA(x), a, b)}

You could also combine these functions into one to be more efficient. So to return the result you want, you could use:

test$ID <- ifelse2(is.na(test$time) | test$type == "A", NA, "1")


@AnandaMahto has addressed why you're getting these results and provided the clearest way to get what you want. But another option would be to use identical instead of ==.

test$ID <- ifelse(is.na(test$time) | sapply(as.character(test$type), identical, "A"), NA, "1")

Or use isTRUE:

test$ID <- ifelse(is.na(test$time) | Vectorize(isTRUE)(test$type == "A"), NA, "1")