Created
March 19, 2017 00:13
-
-
Save tomsing1/d4cca560c27e059e9842b2e2f43745fb to your computer and use it in GitHub Desktop.
Change factor levels conditionally using dplyr and forcats
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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