R how to change one of the levels to NA

I have a dataset and one of its columns has factor levels "a" "b" "c" "NotPerformed" . How to change all "NotPerformed" factors to NA?

+6
source share
2 answers

Set the NA level:

 x <- factor(c("a", "b", "c", "NotPerformed")) x ## [1] abc NotPerformed ## Levels: abc NotPerformed levels(x)[levels(x)=='NotPerformed'] <- NA x ## [1] abc <NA> ## Levels: abc 

Note that the factor level is removed.

+10
source

I am reviewing my old answer and providing what you can do from September 2016. With the development of the dplyr package, you can now use recode_factor() to do the job.

 x <- factor(c("a", "b", "c", "NotPerformed")) # [1] abc NotPerformed # Levels: abc NotPerformed library(dplyr) recode_factor(x, NotPerformed = NA_character_) # [1] abc <NA> # Levels: abc 
+2
source

Source: https://habr.com/ru/post/973944/


All Articles