rconditional-statementsgreplmutate

Using mutate and grepl with multiple conditions


I'm attempting to use mutate and grepl to modify a column based on specific conditions in 2 other columns. One of those conditions is met by matching specific words in one of the columns. Both conditions have to be met. Below is a description of script example of what I'm trying to do:

df <- x %>% 
        mutate(col3 = ifelse(grepl(c("string1"), col1) & grepl(c("string5|string6|string7"), col2), 
                            "new_string",
                             col1))

When using grepl, OR (|) seems to be the only thing that works. I need both conditions to be true. I therefore need to use AND (&) or something of the sort.

Anyone might have a simple solution?


Solution

  • (Note: this is a provisional answer. OP needs to provide more information.)

    The code you have works, provided it matches the data you have. It would be helpful, as Quinten has suggested, if you provided sample data and an expected output. But, to answer the question, of how to use "mutate and grepl with multiple conditions", literally the way you did it is the answer:

    # generate sample data:
    df <- data.frame(
        col1 = paste0("string", 1:2),
        col2 = paste0("string", 1:10))
    
    df %>% 
        mutate(col3 = ifelse(grepl(c("string1"), col1) & grepl(c("string5|string6|string7"), col2), 
                            "new_string",
                                col1))
    

    Output:

          col1     col2       col3
    1  string1  string1    string1
    2  string2  string2    string2
    3  string1  string3    string1
    4  string2  string4    string2
    5  string1  string5 new_string
    6  string2  string6    string2
    7  string1  string7 new_string
    8  string2  string8    string2
    9  string1  string9    string1
    10 string2 string10    string2