I've written the following code in R which works fine. However, assuming I had to apply a similar code to a factor variable with several levels (> 6), ifelse
statements can be quite difficult to read. I'm wondering if there are any other more efficient ways of writing an easy to read code but still using dplyr.
library(dplyr)
mtcars %>% arrange(gear) %>%
mutate(gearW = ifelse(gear == 3, "Three", ifelse(gear == 4, "Four", "Five")))
We can use factor
mtcars %>%
arrange(gear) %>%
mutate(gearW = as.character(factor(gear, levels=3:5,
labels= c("three", "four", "five"))))
Or another option is english
library(english)
mtcars %>%
arrange(gear) %>%
mutate(gearW = as.character(english(gear)))
EDIT: Added the as.character
from @David Arenburg's and @Konrad Rudolph's comments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With