[R] What is wrong with this code?

Peter Ehlers ehlers at ucalgary.ca
Wed Jun 30 22:45:23 CEST 2010


On 2010-06-30 14:28, Erik Iverson wrote:
>
>
> Cable, Samuel B Civ USAF AFMC AFRL/RVBXI wrote:
>>
>>>> Anyway, I still wouldn't mind some advice on character
>>>> matching.
>>>> Thanks.
>>>>
>>> If so we need a reproducible example of what you are doing.
>>
>> OK, let's say I have three strings. Str1="abc". Str2="abcd".
>> Str3="efgh".
>>
>> I want to compare Str1 and Str2 in such a way that R detects that Str2
>> indeed contains Str1. I want something that returns a "TRUE" value.
>> Then I want to compare Str1 and Str3 so that R detects that Str3 does
>> not contain Str1. I don't want it to give me an error because it can't
>> find Str1. I just want to get a "FALSE" value. Is there a way to do
>> this that's less messy than what I came up with? Thanks again.
>
> Str1 <- "abc"
> Str2 <- "abcd"
> Str3 <- "efgh"
>
>  > sapply(list(Str2, Str3), grepl, pattern = Str1)
> [1] TRUE FALSE
>

I think I'd just go with

  grepl(Str1, c(Str2, Str3))

   -Peter Ehlers



More information about the R-help mailing list