How to assign NA as value?

Asked

Viewed 202 times

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 the value occurrences "Nao" for NA, that is, empty field.

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

3

Spin

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

The code enem$TP_COR_RACA=="Nao" will find the rows of the column enem$TP_COR_RACA which are equal to "Nao". It is then sufficient to replace the remarks in these positions by NA.

1

You can use the ifelse also:

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

The ifelse takes three arguments:

  1. A comparison: enem$TP_COR_RACA == "Nao"
  2. Result if comparison is true: NA
  3. Result if false: Enem$TP_COR_RACA (the vector value itself)

It will make the comparison for each element of the vector.


Another way is the function recode_factor 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.