Search code examples
rdplyrtidyverserecode

Convert integers to vector in R using Tidyverse


In my data set, a column holds integer numbers that encode whether there was "no" (0), "slight" (1), or "severe" (2) bleeding after a medical procedure.

How can I turn those integer values into descriptive names? I tried to to it with factor(levels = bleed, labels = c("none", "slight", "severe")), but that does not agree with my Tidyverse-style, %>%-piped data wrangling.

How do I turn those numbers into descriptive labels?


Solution

  • In a tidyverse-like pipeline, you can use the recode function inside a mutate statement

    library(dplyr)
    
    df %>%
      mutate(your_int_var = recode(your_int_var, `0` = 'no', `1` = 'slight', `2` = 'severe'))
    

    or even better using unquote splicing !!!

    values <- c(`0` = 'no', `1` = 'slight', `2` = 'severe')
    
    df %>% 
      mutate(your_int_var = recode(your_int_var, !!!values))