Search code examples
rforcats

fct_recode replace level by NA


I am trying to substitute all "a" in a R factor variable by a NA character using forcats::fct_recode. This is what i tried:

fct <- forcats::as_factor(c("a", "b"))
fct %>% forcats::fct_recode("c" = "a") #works
fct %>% forcats::fct_recode(NA = "a") #error
fct %>% forcats::fct_recode(NA_character_ = "a") #error

Is there a way to achieve my goal with fct_recode?


Solution

  • You need to use backticks to turn the values to NA :

    x1 <- fct %>% forcats::fct_recode(`NA` = "a") 
    x1
    #[1] NA b 
    #Levels: NA b
    

    However, note that although this "looks" like NA it is not real NA. It is string "NA".

    is.na(x1)
    #[1] FALSE FALSE
    
    x1 == 'NA'
    #[1]  TRUE FALSE
    

    To make it real NA replace it to NULL.

    x2 <- fct %>% forcats::fct_recode(NULL = "a")
    x2
    #[1] <NA> b   
    #Levels: b
    
    is.na(x2)
    #[1]  TRUE FALSE