How to include NA in ifelse?

前端 未结 5 646
走了就别回头了
走了就别回头了 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 03:46

    You might also try an elseif.

    x <- 1
    if (x ==1){
        print('same')
    } else if (x > 1){
        print('bigger')
    } else {
        print('smaller')
    }
    
    0 讨论(0)
  • 2020-12-15 03:54

    So, I hear this works:

    Data$X1<-as.character(Data$X1)
    Data$GEOID<-as.character(Data$BLKIDFP00)
    Data<-within(Data,X1<-ifelse(is.na(Data$X1),GEOID,Data$X2)) 
    

    But I admit I have only intermittent luck with it.

    0 讨论(0)
  • 2020-12-15 04:00

    @AnandaMahto has addressed why you're getting these results and provided the clearest way to get what you want. But another option would be to use identical instead of ==.

    test$ID <- ifelse(is.na(test$time) | sapply(as.character(test$type), identical, "A"), NA, "1")
    

    Or use isTRUE:

    test$ID <- ifelse(is.na(test$time) | Vectorize(isTRUE)(test$type == "A"), NA, "1")
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 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")
    
    0 讨论(0)
提交回复
热议问题