R how to change one of the level to NA

lolibility picture lolibility · Aug 18, 2014 · Viewed 9.9k times · Source

I have a data set and one of its column has factor levels "a" "b" "c" "NotPerformed". How can I change all the "NotPerformed" factors to NA?

Answer

Matthew Lundberg picture Matthew Lundberg · Aug 18, 2014

Set the level to NA:

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

Note that the factor level is removed.