Search code examples
rdplyrmagrittr

R Assigning multiple classes if value fall between ranges in a vector (Simple way)


I'm trying to assign a class to values if they are in a certain range. Here is an example:

library(dplyr)
library(data.table)
library(magrittr)

fieldArea = tibble(TotalFieldArea= runif(100000) * 1000)

fieldArea %<>%
  mutate(Segment2019 = if_else(TotalFieldArea < 99, "Very_Small",
                       if_else(TotalFieldArea < 199, "Small",
                       if_else(TotalFieldArea < 499, "Medium",
                       if_else(TotalFieldArea < 999, "Large", "Key_Account")))))

I just wonder if there is a way of simplifying the code in dplyr with something like:

# Designing rules
class_rule = c(0, 99, 199, 499, 999)
classes    = c("Very_Small", "Small", "Medium", "Large", "Key_Account")

# Applying rules - (Imaginary Code)
fieldArea %<>% mutate(Segment2019 = classes %in% TotalFieldArea < class_rule)

The classes should be assigned if they fall in the range.


Solution

  • We can use cut

    library(dplyr)
    fieldArea %>%
           mutate(Segment2019 = cut(TotalFieldArea, breaks = c(class_rule, Inf), 
          labels = classes))