Search code examples
rif-statementdplyrcase-when

Case When LIKE equivalent in R


I am wanting to do similar to a case statement in r for a variable utilizing an ifelse statement. For example, lets say I have the following column vector 'Letter_Test' in a data frame that has:

Alpha - Test, Beta- Test, Zeta-Test, Alpha-Two, Beta-Two

I'd like to write a statement that says basically if data is like Alpha then 'Alpha', else return the column result.

In SQL that would be (CASE WHEN Letter_Test LIKE '%Alpha%' THEN Alpha else 'Letter-Test' end).


Solution

  • Actually not sure if I got the question right but if you mean you want to test if "Alpha" is in the column Letter-Test, then this works:

        > df <- data.frame("Letter-Test" = c("Alpha - Test", "Beta- Test", "Zeta-Test", "Alpha-Two", "Beta-Two"),
    +                  stringsAsFactors = FALSE)
    > 
    > ifelse(test = grepl("Alpha", df$Letter.Test), yes = "Alpha", no = df$Letter.Test)
    [1] "Alpha"      "Beta- Test" "Zeta-Test"  "Alpha"      "Beta-Two"  
    

    Test takes TRUE and FALSE, grepl returns TRUE if the word was found inside the column Letter.Test.

    Or you can put the results directly into a new column in the data frame:

    > df$AplhaTest <- ifelse(test = grepl("Alpha", df$Letter.Test), yes = "Alpha", no = df$Letter.Test)
    > df
       Letter.Test  AplhaTest
    1 Alpha - Test      Alpha
    2   Beta- Test Beta- Test
    3    Zeta-Test  Zeta-Test
    4    Alpha-Two      Alpha
    5     Beta-Two   Beta-Two