Skip to content

Instantly share code, notes, and snippets.

@tomsing1
Created March 19, 2017 00:13
Show Gist options
  • Save tomsing1/d4cca560c27e059e9842b2e2f43745fb to your computer and use it in GitHub Desktop.
Save tomsing1/d4cca560c27e059e9842b2e2f43745fb to your computer and use it in GitHub Desktop.
Change factor levels conditionally using dplyr and forcats
library(dplyr)
library(forcats)
# encode the 'Month' column of the 'airquality' dataset as a factor
airquality2 <- airquality %>%
dplyr::mutate(
Month = factor(Month),
Month = forcats::fct_recode(Month, May = "5", June = "6", July = "7",
August = "8", September = "9")
)
levels(airquality2$Month)
# recode 'Month' as 'X' whenever the 'Day' column is even
airquality2 %>%
dplyr::mutate(
Month = dplyr::if_else(
Day %% 2 == 0,
# must return a factor
factor("X", levels = c("X", levels(Month))), # with the right levels
factor(Month)
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment