How to include NA in ifelse?

前端 未结 5 657
走了就别回头了
走了就别回头了 2020-12-15 03:05

I am trying to create a column ID based on logical statements for values of other columns. For example, in the following dataframe

test <- st         


        
5条回答
  •  情话喂你
    2020-12-15 04:08

    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")
    

提交回复
热议问题