What's the R equivalent of SQL's LIKE 'description%' statement?

Viewed 77923

Not sure how else to ask this but, I want to search for a term within several string elements. Here's what my code looks like (but wrong):

inplay = vector(length=nrow(des))
for (ii in 1:nrow(des)) {
 if (des[ii] = 'In play%')
  inplay[ii] = 1
 else inplay[ii] = 0
}

des is a vector that stores strings such as "Swinging Strike", "In play (run(s))", "In play (out(s) recorded)" and etc. What I want inplay to store is a 1s and 0s vector corresponding with the des vector, with the 1s in inplay indicating that the des value had "In play%" in it and 0s otherwise.

I believe the 3rd line is incorrect, because all this does is return a vector of 0s with a 1 in the last element.

Thanks in advance!

4 Answers

str_like from the stringr package development version (as of 2022-09-10) follows the structure of SQL's LIKE:

devtools::install_github("tidyverse/stringr")
library(stringr)

fruit <- c("apple", "banana", "pear", "pineapple")
str_like(fruit, "app%")
#[1]  TRUE FALSE FALSE FALSE

Not only does it include %, but also several other operators (see ?str_like).

  • Must match the entire string

  • _⁠ matches a single character (like .)

  • ⁠%⁠ matches any number of characters (like ⁠.*⁠)

  • ⁠%⁠ and ⁠_⁠ match literal ⁠%⁠ and ⁠_⁠

  • The match is case insensitive by default

Related