how to remove a specific factor level to missing value in r?

Viewed 497

I got a factor data set df that looks like this:

df <- data.frame(attend = c("yes", "no", "no", "iap", "yes", "yes", "iap"),
           sex = c("male", "female", "female", "male", "female", "male", "female"))

df$attend <- as.factor(df$attend)
df$sex <- as.factor(df$sex)

df
attend sex
yes male
no female
no female
iap male
yes female
yes male
iap female

I want to remove only the iap level from the attend variable.(I don't want to remove the entire row, what I'm looking for is to remove the level iap, so that it becomes a missing value under variable attend)

I tried the below code to remove it but it occurs an error saying: Error in UseMethod("droplevels") : no applicable method for 'droplevels' applied to an object of class "character".

df$attend <- droplevels(levels(df$attend)[4])

Much appreciated it if someone can help.

2 Answers

You can change the levels of the variable -

levels(df$attend)[levels(df$attend) == 'iap'] <- NA
df

#  attend    sex
#1    yes   male
#2     no female
#3     no female
#4   <NA>   male
#5    yes female
#6    yes   male
#7   <NA> female

This will also automatically drop the 'iap' as level.

levels(df$attend)
#[1] "no"  "yes"

Here we can also use forcats::fct_recode to turn specific values to NA.

df$attend <- forcats::fct_recode(df$attend, NULL = 'iap')

Another base R solution would be using exclude:

df$attend <- factor(df$attend, exclude = "iap")
  attend    sex
1    yes   male
2     no female
3     no female
4   <NA>   male
5    yes female
6    yes   male
7   <NA> female
Related