How to Use the str_like() Function in R

The str_like() function in R is “used to detect a pattern in the same way as SQL’s LIKE operator”. It checks whether a character string matches a pattern specified as a string and returns a logical vector of the same length as the input vector, with TRUE suggesting a match and FALSE suggesting no match.

Syntax

str_like(string, pattern, ignore_case = TRUE)

Parameters

  1. string: Input vector. Either a character vector or something coercible to one.
  2. pattern: A character vector containing a SQL “like” pattern.
  3. ignore_case: Ignore case of matches? Defaults to TRUE to match the SQL LIKE operator.

Example 1

library(stringr)

cars <- c("BMW", "Audi", "Mercedez", "Porche")
str_like(cars, "Mercedez")

Output

[1] FALSE FALSE TRUE FALSE

Example 2

library(stringr)

cars <- c("bmw", "Audi", "Mercedez", "Porche")
pattern <- "b__"

str_like(cars, pattern)

Output

[1] TRUE FALSE FALSE FALSE

Conclusion

The str_like() function follows the conventions of the SQL LIKE operator.

  1. It must match the entire string.
  2. The _ matches a single character (like .).
  3. The % matches any number of characters (like .*).
  4. The \% and \_ match literal % and _.
  5. The match is case-insensitive by default.

That’s it.

Leave a Comment