寻找R语言中可检测字符串包含子串并返回布尔值的函数
Hey there! Let's figure out how to get that exact contains(string, substring) behavior you're looking for.
First off, base R actually has a built-in function that does exactly what you need—returns a boolean for substring presence: grepl(). The catch is its parameter order is a bit different from your ideal function: it takes the substring first, then the target string. For your example:
string <- "12345REFUND4567" substring <- "REFUND" grepl(substring, string) # Returns TRUE
If you want to stick strictly to the contains(string, substring) call format you imagined, it's super easy to wrap grepl() into a custom function. Even better, we can add fixed = TRUE to ensure it matches the substring literally (no accidental regex pattern matching if your substring has special characters like . or *):
contains <- function(string, substring) { grepl(substring, string, fixed = TRUE) } # Now use it exactly how you wanted: contains(string, substring) # Returns TRUE
Wait, you mentioned you tried str_detect() and it didn't work—let me double-check that. From the stringr package, str_detect() does return a boolean, but its parameter order is reversed from grepl(): it takes the target string first, then the pattern. So for your example, this should work too:
library(stringr) str_detect(string, substring) # Also returns TRUE
Maybe you had the parameters swapped before? That's a common mix-up between base R and tidyverse string functions!
So to recap your options:
- Use base R's
grepl()directly (remembergrepl(substring, string)) - Build your own
contains()function for the exact syntax you want - Double-check parameter order if you go back to
str_detect()
内容的提问来源于stack exchange,提问作者Luca Foerster

