How to ignore NA in ifelse statement

别来无恙 提交于 2019-12-17 16:35:41

问题


I came to R from SAS, where numeric missing is set to infinity. So we can just say:

positiveA = A > 0;

In R, I have to be verbose like:

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

I find this syntax is hard to read. Is there anyway I can modify ifelse function to consider NA a special value that is always false for all comparison conditions? If not, considering NA as -Inf will work too.

Similarly, setting NA to '' (blank) in ifelse statement for character variables.

Thanks.


回答1:


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



回答2:


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.




回答3:


Try this:

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



回答4:


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



回答5:


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


来源:https://stackoverflow.com/questions/13598511/how-to-ignore-na-in-ifelse-statement

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