Search code examples
rtidyverserecode

Recode a range of values into one number using 'recode()' in tidyverse


I am working with a very messy data set and I'll be needing to use the recode() function in a pipe to turn numbers 0:30 into four numerical categories (0,1,2,3,4).

What I have:

recode(var, 10:30 = 4,
              6:9 = 3,
              3:5 = 2,
              1:2 = 1,
              0 = 0))

Any help is greatly appreciated!


Solution

  • It may be easier with case_when

    library(dplyr)
    case_when(var %in% 10:30 ~ 4,
                   var %in% 6:9 ~ 3, 
                   var %in% 3:5 ~ 2,
                   var %in% 1:2 ~ 1, 
                    var == 0 ~ 0)
    

    Or another option is cut

    as.integer(cut(var, breaks = c(-Inf, 0, 2, 5, 9, 30, Inf)))
    

    NOTE: change the include.lowest and right option in cut to adjust

    data

    set.seed(24)
    var <- sample(0:35, 50, replace = TRUE)