How to assign NA as value?

5

I have the following line of code:

enem$TP_COR_RACA <- factor(enem$TP_COR_RACA, levels = 0:5, 
  labels = c("Nao", "Branca", "Preta", "Parda", "Amarela", "Indígena"))

I want to replace occurrences of the "Nao" value with NA , ie empty field.

    
asked by anonymous 29.03.2017 / 16:58

3 answers

6

As you are using factors, you can also directly change the levels :

levels(enem$TP_COR_RACA)[levels(enem$TP_COR_RACA) == "Nao"] <- NA
    
29.03.2017 / 23:50
3

Run

enem$TP_COR_RACA[enem$TP_COR_RACA=="Nao"] <- NA

The code enem$TP_COR_RACA=="Nao" will find the lines of the enem$TP_COR_RACA column that are equal to "Nao" . Then, simply replace the observations present in these positions with NA .

    
29.03.2017 / 18:22
0

You can use ifelse also:

enem$TP_COR_RACA <- ifelse(enem$TP_COR_RACA == "Nao", NA, enem$TP_COR_RACA)

The ifelse gets three arguments:

  • A comparison: enem$TP_COR_RACA == "Nao"
  • Result if the comparison is true: NA
  • Result if false: enem $ TP_COR_RACA (the vector value itself)
  • It will do the comparison for each element of the vector.

    Another way is the recode_factor function of dplyr .

    Example:

    > a <- factor(c("a", "b", "c", "Não", "a"))
    > recode_factor(a, 'Não' = NA_character_)
    [1] a    b    c    <NA> a   
    Levels: a b c
    
        
    31.03.2017 / 20:02