How to ignore NA in ifelse statement

丶灬走出姿态 提交于 2019-11-27 23:55:49

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.

Peter S

Try this:

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

YOu can use the missing argument i if_else_ from hablar:

library(hablar) 

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

if_else_(x > 0, T, F, missing = F)

which gives you

[1] FALSE  TRUE FALSE FALSE

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!