Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R how to change one of the level to NA

Tags:

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?

like image 477
lolibility Avatar asked Aug 18 '14 00:08

lolibility


People also ask

How do I redefine a level in R?

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.

How do you get the NA factor?

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 .

How do you add a factor to a NA in R?

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.

How do I drop a level in R?

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.


1 Answers

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.

like image 122
Matthew Lundberg Avatar answered Oct 14 '22 13:10

Matthew Lundberg