How to ignore NA in ifelse statement

This syntax is easier to read:

x <- c(NA, 1, 0, -1)

(x > 0) & (!is.na(x)) 
# [1] FALSE  TRUE FALSE FALSE

(The outer parentheses aren't necessary, but will make the statement easier to read for almost anyone other than the machine.)


Edit:

## If you want 0s and 1s
((x > 0) & (!is.na(x))) * 1
# [1] 0 1 0 0

Finally, you can make the whole thing into a function:

isPos <- function(x) {
    (x > 0) & (!is.na(x)) * 1
}

isPos(x)
# [1] 0 1 0 0

Replacing a NA value with zero seems rather strange behaviour to expect. R considers NA values missing (although hidden far behind scenes where you (never) need to go they are negative very large numbers when numeric ))

All you need to do is A>0 or as.numeric(A>0) if you want 0,1 not TRUE , FALSE

# some dummy data
A <- seq(-1,1,l=11)
# add NA value as second value
A[2] <- NA
positiveA <- A>0
positiveA
 [1] FALSE    NA FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE

 as.numeric(positiveA) # 
 [1]  0 NA  0  0  0  0  1  1  1  1  1

note that ifelse(A>0, 1,0) would also work.

The NA values are "retained", or dealt with appropriately. R is sensible here.


Try this:

positiveA <- ifelse(!is.na(A) & A > 0, 1, 0)

If you are working with integers you can use %in%

For example, if your numbers can go up to 2

test <- c(NA, 2, 1, 0, -1)

other people has suggested to use

(test > 0) & (!is.na(test))
or
ifelse(!is.na(test) & test > 0, 1, 0)

my solution is simpler and gives you the same result.

test %in% 1:2