[R] %in% operator - NOT IN

(Ted Harding) ted.harding at wlandres.net
Sun May 8 11:35:07 CEST 2011

On 08-May-11 09:18:55, Berwin A Turlach wrote:
> G'day Dan,
> On Sun, 8 May 2011 05:06:27 -0400
> Dan Abner <dan.abner99 at gmail.com> wrote:
>> Hello everyone,
>> I am attempting to use the %in% operator with the ! to produce
>> a NOT IN type of operation. Why does this not work? Suggestions?
>> > data2[data1$char1 %in% c("string1","string2"),1]<-min(data1$x1)
>> > data2[data1$char1 ! %in%
>> > c("string1","string2"),1]<-max(data1$x1)+1000
>> Error: unexpected '!' in "data2[data1$char1 !"
> Try (untested)
> R> data2[!(data1$char1 %in%
> c("string1","string2")),1]<-max(data1$x1)+1000 
> HTH.
> Cheers,
>       Berwin

Berwin's suggestion should work -- it is the general way to
negate the result of an "%in".

As to "Why does this not work?", the point to note is that
"%in%" is a binary operator. If you enter
you will be taken to the help page for "match", where it is
pointed out that:

  ?%in%? is a more intuitive interface as a binary operator,
  which returns a logical vector indicating if there is a
  match or not for its left operand.

Specifically, therefore, the syntax of "%in%" requires

  X %in% Y

where X and Y are objects to which the functional definition
of %in% applies (see the same help page):

  '%in%' is currently defined as
  '"%in%" <- function(x, table) match(x, table, nomatch = 0) > 0'

In your expression (effectively "X ! %in% Y") the item which
immediately precedes "%in%" is the "!", and this is not a
valid item!

Based on the above functional definition, you could define
your own binary operator "%!in%" as

"%!in%" <- function(x,table) match(x,table, nomatch = 0) == 0

or similar -- I have not tested this so cannot guarantee it!
However, it is the way to proceed if you want a "NOT IN".
Then the usage could be:

data2[data1$char1 %!in% c("string1","string2"),1]<-max(data1$x1)+1000

Hoping ths helps,

E-Mail: (Ted Harding) <ted.harding at wlandres.net>
Fax-to-email: +44 (0)870 094 0861
Date: 08-May-11                                       Time: 10:35:05
------------------------------ XFMail ------------------------------

More information about the R-help mailing list