Creating New DF Column that Assigns a Label based on Conditions from Another Column

Hi,

This is an example of how to do it using dplyr::mutate() and a little help of the stringr package which enables the use of "Regular Expressions" to avoid too much typing.

library(dplyr)
library(stringr)

# Sample data on a copy/paste friendly format
sample_df <- data.frame(
  stringsAsFactors = FALSE,
          Assigned = c("Name 1", "Name 1", "Name 3", "Name 4", "Name 2"),
     Assigned_Type = c("ISR", "ISR", "Sales Lead", "Sales Lead", "ISR")
)

sample_df %>% 
    mutate(new_column = if_else(str_detect(Assigned, "(1|2)$"), "ISR", "Sales Lead"))
#>   Assigned Assigned_Type new_column
#> 1   Name 1           ISR        ISR
#> 2   Name 1           ISR        ISR
#> 3   Name 3    Sales Lead Sales Lead
#> 4   Name 4    Sales Lead Sales Lead
#> 5   Name 2           ISR        ISR

Created on 2020-10-07 by the reprex package (v0.3.0)

If you want to learn more about data wrangling you can read this free ebook

Also, for future questions please try to provide a proper REPRoducible EXample (reprex) illustrating your issue.

1 Like