How to include NA in ifelse?

前端 未结 5 650
走了就别回头了
走了就别回头了 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

    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
    

提交回复
热议问题