Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ifelse statement with mutate in dplyr

Tags:

dataframe

r

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")))
like image 377
John_dydx Avatar asked Jan 13 '16 16:01

John_dydx


1 Answers

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.

like image 72
akrun Avatar answered Sep 24 '22 08:09

akrun