mbeasle2
mbeasle2

Reputation: 163

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!

Upvotes: 1

Views: 4417

Answers (2)

Kemi
Kemi

Reputation: 1

Colons weren't working for me so I ended up with another solution:

case_when(
    var == 0 ~ 0,
    between(var, 10, 30) ~ 4,
    between(var, 6, 9) ~ 3,
    between(var, 3, 5) ~ 2,
    between(var, 1, 2) ~ 1
  ))

Upvotes: 0

akrun
akrun

Reputation: 886928

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)

Upvotes: 3

Related Questions