Case when in R can be executed with case_when() function in dplyr package. Dplyr package is provided with case_when() function which is similar to case when statement in SQL.
We will be using iris data to depict the example of case_when() function.
library(dplyr) mydata2 <-iris head(mydata2)
iris data will be looking like
We will be creating additional variable species_new using mutate function and case when statement.
mydata2 %>% mutate(species_new = case_when(is.na(Species) ~ "missing", Species=="setosa" ~ "setosa_new", Species=="versicolor" ~ "versicolor_new", Species=="virginica" ~ "virginica_new", TRUE ~ "others"))
- you can use variables directly within case_when() wrapper.
- TRUE equivalent to ELSE statement .
So the snapshot of resultant data frame will be
NOTE: Make sure you set is.na() condition at the beginning of R case_when to handle the missing values.