Search code examples
rlogical-operatorsdplyr

Cant use mutate() with multiple conditions from same column with dplyr


I want to create a new column (newcol) with mutate() in a tibble(data). The values in the new column(newcol) depend on the values in another column (othercol).

unique(data$othercol)
[1] "1"  "A"  "A1" "A3" "B"  "B2" "C2" "D"  "E"  "F"  "G" 

If othercol is "A", "A1", "A3", I want to translate into 1 in newcol, otherwise newcol should be 0.

I tried several codes but failed. It may all come down to my lack of experience with dplyr and logical operators

What should I do?

Thanks


Solution

  • We can use %in% to create a logical vector

    library(dplyr)
    data <- data %>%
               mutate(newcol = as.integer(othercol %in% c('A', 'A1', 'A3')))
    

    Or using ifelse

    data <- data %>%
               mutate(newcol = ifelse(othercol %in% c('A', 'A1', 'A3'), 1, 0))
    

    Or using str_detect

    library(stringr)
    data <- data %>%
               mutate(newcol = +(str_detect(othercol, '^A\\d*$')))
    

    Or using grepl

    data$newcol <- +(grepl("^A\\d*$", data$othercol))