[R] is there a function like %in% for characters?
Douglas Bates
bates at stat.wisc.edu
Sun Apr 17 20:31:02 CEST 2005
Sundar Dorai-Raj wrote:
>
>
> Terry Mu wrote on 4/2/2005 9:38 PM:
>
>> like:
>>
>> "a" %in% "abcd"
>> TRUE
>>
>> Thanks.
>>
>
>
> See ?regexpr.
>
> regexpr("a", "abcd") > 0
>
> However, the first argument is not vectorized so you may also need
> something like:
>
> > sapply(c("a", "b", "e"), regexpr, c("abcd", "bcde")) > 0
> a b e
> [1,] TRUE TRUE FALSE
> [2,] FALSE TRUE TRUE
Alternatively you could use strsplit to split the original string into
individual characters then fall back on %in%. The only complication is
that strsplit will return a list of one character vector and you must
unlist it to get the character vector itself.
> strsplit("abcf", "")
[[1]]
[1] "a" "b" "c" "f"
> "a" %in% unlist(strsplit("abcf", ""))
[1] TRUE
> "a" %in% unlist(strsplit("bcdf", ""))
[1] FALSE
More information about the R-help
mailing list