我试图确定一个字符串是否是另一个字符串的子集。例如:
chars <- "test"
value <- "es"
如果“value”作为字符串“chars”的一部分出现,我想返回TRUE。在下面的场景中,我想返回false:
chars <- "test"
value <- "et"
我试图确定一个字符串是否是另一个字符串的子集。例如:
chars <- "test"
value <- "es"
如果“value”作为字符串“chars”的一部分出现,我想返回TRUE。在下面的场景中,我想返回false:
chars <- "test"
value <- "et"
当前回答
你想要grepl:
> chars <- "test"
> value <- "es"
> grepl(value, chars)
[1] TRUE
> chars <- "test"
> value <- "et"
> grepl(value, chars)
[1] FALSE
其他回答
你想要grepl:
> chars <- "test"
> value <- "es"
> grepl(value, chars)
[1] TRUE
> chars <- "test"
> value <- "et"
> grepl(value, chars)
[1] FALSE
同样,可以使用"stringr"库:
> library(stringr)
> chars <- "test"
> value <- "es"
> str_detect(chars, value)
[1] TRUE
### For multiple value case:
> value <- c("es", "l", "est", "a", "test")
> str_detect(chars, value)
[1] TRUE FALSE TRUE FALSE TRUE
使用grepl函数
grepl( needle, haystack, fixed = TRUE)
像这样:
grepl(value, chars, fixed = TRUE)
# TRUE
使用?grepl获取更多信息。
如果你也想检查一个字符串(或一组字符串)是否包含多个子字符串,你也可以在两个子字符串之间使用'|'。
>substring="as|at"
>string_vector=c("ass","ear","eye","heat")
>grepl(substring,string_vector)
你会得到
[1] TRUE FALSE FALSE TRUE
因为第一个单词包含子字符串“as”,而最后一个单词包含子字符串“at”
你可以使用grep
grep("es", "Test")
[1] 1
grep("et", "Test")
integer(0)