John_dydx
John_dydx

Reputation: 961

ifelse statement with mutate in dplyr

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")))

Upvotes: 5

Views: 6721

Answers (1)

akrun
akrun

Reputation: 887048

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.

Upvotes: 5

Related Questions