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?
The simplest way to rename multiple factor levels is to use the levels() function. For example, to recode the factor levels “A”, “B”, and “C” you can use the following code: levels(your_df$Category1) <- c("Factor 1", "Factor 2", "Factor 3") . This would efficiently rename the factors “Factor 1” and so on.
You can use addNA() . addNA modifies a factor by turning NA into an extra level (so that NA values are counted in tables, for instance). So another reason this is nice is because if you already have a factor f , you can use addNA() to quickly add NA as a factor level without changing f .
The codes of a factor may contain NA . For a numeric x , set exclude=NULL to make NA an extra level ( "NA" ), by default the last level. If "NA" is a level, the way to set a code to be missing is to use is.na on the left-hand-side of an assignment.
The droplevels() function in R can be used to drop unused factor levels. This function is particularly useful if we want to drop factor levels that are no longer used due to subsetting a vector or a data frame. where x is an object from which to drop unused factor levels.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With