Ifelse with mutation in dplyr

I wrote the following code in R, which works fine. However, assuming that I had to apply similar code to a factor variable with several levels (> 6), ifelse statements can be quite difficult to read. I am wondering if there are other more efficient ways to write easy-to-read code, but dplyr is used.

  library(dplyr) mtcars %>% arrange(gear) %>% mutate(gearW = ifelse(gear == 3, "Three", ifelse(gear == 4, "Four", "Five"))) 
+5
source share
1 answer

We can use factor

 mtcars %>% arrange(gear) %>% mutate(gearW = as.character(factor(gear, levels=3:5, labels= c("three", "four", "five")))) 

Or another option: english

 library(english) mtcars %>% arrange(gear) %>% mutate(gearW = as.character(english(gear))) 

EDIT: added as.character comments from @David Arenburg and @Konrad Rudolph.

+5
source

Source: https://habr.com/ru/post/1240550/


All Articles