[R] regex -> negate a word

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Sun Jan 18 20:38:45 CET 2009


Jorge Ivan Velez wrote:
> Hi Wacek,
> I think you wanted to say "strings" instead "x" in your last line  : )
>
>   

of course, thanks.  the correct version is:

if(length(matching <- grep(pattern, strings)))
   strings[-matching]
   else strings

btw., and in relation to a recent post complaining about how the mailing
list is maintained, i must say that although the idea that posts could
be edited after they've been sent does may not sound good in general, i
think it would be useful to be able to just fix such minor typos in
place instead of posting a correction.  after all, the list is intended
to serve as help to those who care not only to ask, but also to browse
the archives.  but this is a side comment, i take no sides and make no
recommendations.


vQ




> Best,
>
> Jorge
>
>
> On Sun, Jan 18, 2009 at 2:22 PM, Wacek Kusnierczyk <
> Waclaw.Marcin.Kusnierczyk at idi.ntnu.no> wrote:
>
>   
>> Rau, Roland wrote:
>>     
>>> Dear all,
>>>
>>> let's assume I have a vector of character strings:
>>>
>>> x <- c("abcdef", "defabc", "qwerty")
>>>
>>> What I would like to find is the following: all elements where the word
>>> 'abc' does not appear (i.e. 3 in this case of 'x').
>>>
>>>       
>> a quick shot is:
>>
>> x[-grep("abc", x)]
>>
>> which unfortunately fails if none of the strings in x matches the
>> pattern, i.e., grep returns integer(0); arguably, x[integer(0)] should
>> rather return all elements of x:
>>
>> "An empty index selects all values" (from ?'[')
>>
>> but apparently integer(0) does not count as an empty index (and neither
>> does NULL).  so you may want something like:
>>
>> strings = c("abcdef", "defabc", "qwerty")
>> pattern = "abc"
>> if (length(matching <- grep(pattern, strings))) x[-matching] else x
>>
>> vQ
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>>




More information about the R-help mailing list