Drthm1456
Drthm1456

Reputation: 479

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).

Upvotes: 2

Views: 6864

Answers (4)

Simon Stolz
Simon Stolz

Reputation: 237

As Rahim posted: Use the case_when() and %like% predicate.

case_when(
      species %like% "Alpha"    ~ "Alpha",
      TRUE                      ~  "Beta"
    )

And I want to add to JD Longs comment (which i am not allowed to comment on): %like% seems to come from the DescTools package https://www.rdocumentation.org/packages/DescTools/versions/0.99.30/topics/%25like%25

Upvotes: 0

Rahim
Rahim

Reputation: 186

Use the case_when() and %like% predicate.

case_when(
      species %like% "Alpha"        ~ "Alpha",
      TRUE                      ~  "Alpha"
    )

Upvotes: 3

JBGruber
JBGruber

Reputation: 12410

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

Upvotes: 2

AidanGawronski
AidanGawronski

Reputation: 2085

One option:

new_thing <- ifelse("Alpha" %in%  df$Letter_Test, "Alpha", "Letter-Test")

Another option:

new_thing2 <- gsub(".*(Alpha).*", "\\1", df$Letter_Test)

Upvotes: 0

Related Questions