[R] Odd behaviour of removing 'nothing' from an array or data frame

Peter Dalgaard p.dalgaard at biostat.ku.dk
Tue Oct 31 17:21:49 CET 2006


"hadley wickham" <h.wickham at gmail.com> writes:

> > As Peter said, it's the value that counts, not the way you calculated
> > it.  If you print -c(2,3,5) you get three negative numbers.  If you
> > print -integer(0), you don't get any.  The first case is asking for
> > elements to be left out, the second isn't.
> >
> > The moral of the story is to use logical indices rather than negative ones:
> >
> > dubious.records <- peoples.heights$heights > 2.5
> > peoples.heights = peoples.heights[!dubious.records,]
> 
> Unfortunately, there are some "matching" functions that return numeric
> indices, not logical vectors (eg. grep).  For this case I created an
> "unwhich" function - but is there a better way to proceed?

How about 

negIndex <- function(x) if (length(x)) -x else TRUE
> x <- 1:10
> x[negIndex(which(x>4))]
[1] 1 2 3 4
> x[negIndex(which(x>11))]
 [1]  1  2  3  4  5  6  7  8  9 10

Of course in this case, you can just avoid the which() bit entirely
and do

> x[!(x>4)]
[1] 1 2 3 4
> x[!(x>11)]
 [1]  1  2  3  4  5  6  7  8  9 10


-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907



More information about the R-help mailing list