Recode function (dplyr) does not accept numeric ranges

3

Consider the vector:

x<-runif(30,20,100)

I would like to categorize this vector with the recode function of the package dplyr . The intervals can be arbitrary. For example:

  • from 20 to 50 = 1
  • from 51 to 75 = 2
  • from 76 to 100 = 3

I know I can use other packages and functions to perform this action. But, my intention is specifically to do this with the function recode of dplyr . I have tried this in many ways, but so far I have not been successful.

    
asked by anonymous 08.12.2018 / 07:12

1 answer

5

The easiest way to do this is in base R with the findInterval function. The appropriate dplyr function will be case_when , not recode . Here are two ways.

library(dplyr)

set.seed(1234)
x <- runif(30, 20, 100)

y1 <- case_when(
    20 <= x & x <= 50 ~ 1L,
    50 < x & x <= 75 ~ 2L,
    75 < x ~ 3L,
    TRUE ~ NA_integer_
)

y2 <- findInterval(x, c(20, 50, 75))

identical(y1, y2)
#[1] TRUE

Editing.

After the

08.12.2018 / 13:06