[R] subset

Marc Schwartz marc_schwartz at comcast.net
Mon Mar 26 22:14:07 CEST 2007


On Mon, 2007-03-26 at 15:43 -0400, Liaw, Andy wrote:
> From: Thomas Lumley
> > 
> > On Mon, 26 Mar 2007, Marc Schwartz wrote:
> > 
> > > Sergio,
> > >
> > > Please be sure to cc: the list (ie. Reply to All) with follow up 
> > > questions.
> > >
> > > In this case, you would use %in% with a negation:
> > >
> > > NewDF <- subset(DF, (var1 == 0) & (var2 == 0) & (!var3 %in% 2:3))
> > >
> > 
> > Probably a typo: should be !(var3 %in% 2:3) rather than (!var 
> > %in% 2:3)
> 
> I used to think so, but found I didn't need the parens:
> 
> R> a <- 1:3; b <- c(1, 3, 5)
> R> ! a %in% b
> [1] FALSE  TRUE FALSE
> R> ! (a %in% b)
> [1] FALSE  TRUE FALSE
> 
> Andy

Thanks Andy, you beat me to it  :-)

Just for the explicit sake of the variation as I used in my reply above:

> (!a %in% b)
[1] FALSE  TRUE FALSE


I suspect that Thomas may be fearing the following scenario:

> !a
[1] FALSE FALSE FALSE

> (!a) %in% b
[1] FALSE FALSE FALSE


If one looks at ?Syntax, the negation operator '!' is listed 5 rows
after '%any%' relative to precedence of operation, so our examples above
worked as documented.

HTH,

Marc



More information about the R-help mailing list