Elegant Code with Case_when

Is there an elegant way to write the below code? Please I need assistance

Create a new variable for technical and non-technical items
mutate(structure_type = case_when(
str_detect(text, "Fault")~"Technical",
str_detect(text, "Fallen")~"Technical",
str_detect(text, "transformer")~"Technical",
str_detect(text, "wire")~"Technical",
str_detect(text, "darkness")~"Technical",
str_detect(text, "meter")~"Non-Technical",
str_detect(text, "bill")~"Non-Technical",
str_detect(text, "reconciliation")~"Non-Technical",
str_detect(text, "payment")~"Non-Technical",
TRUE ~ "Additional Review"
))

I don't know if it is elegant but you can make it shorter this way

mutate(structure_type = case_when(
    str_detect(text, "Fault|Fallen|transformer|wire|darkness")~"Technical",
    str_detect(text, "meter|bill|reconciliation|payment")~"Non-Technical",
    TRUE ~ "Additional Review"))
2 Likes

And you can make it more general like this, if you have the options in two vectors of strings.

mutate(structure_type = case_when(
    str_detect(text, str_c(tech_vec, "|")) ~ "Technical",
    str_detect(text, str_c(non_tech_vec, "|")) ~ "Non-Technical",
    TRUE ~ "Additional Review"))
2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.