You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

寻找R语言中可检测字符串包含子串并返回布尔值的函数

在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 (remember grepl(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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:54:52