[R] Transforming boolean subsetting into index subsetting

William Dunlap wdunlap at tibco.com
Sat Jun 29 03:00:09 CEST 2013


And there is no real magic in which().  You already know that
   V[I]
where 'I' is a logical vector the length of 'V' extracts the values
in 'V' corresponding to the TRUE's in 'I'.  Replace 'V' with the vector
made by seq_along(I), (== 1, 2, ..., length(I)), and you have the
essentials of which(I).

which(I) does add an extra twist - it considers missing values in I to be the
same as FALSE's:
   seq_along(I)[ !is.na(I) & I ]

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com

> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of Bert Gunter
> Sent: Friday, June 28, 2013 5:01 PM
> To: Julio Sergio
> Cc: r-help at stat.math.ethz.ch
> Subject: Re: [R] Transforming boolean subsetting into index subsetting
> 
> ?which
> 
> -- Bert
> 
> On Fri, Jun 28, 2013 at 2:58 PM, Julio Sergio <juliosergio at gmail.com> wrote:
> > One of the techniques to subset, a vector for instance, is the following:
> >
> >   V <- c(18, 8, 5, 41, 8, 7)
> >   V
> >   ## [1] 18  8  5 41  8  7
> >   ( I <- abs(V - 9) <= 3 )
> >   ## [1] FALSE  TRUE FALSE FALSE  TRUE  TRUE
> >   V[I]
> >   ## [1] 8 8 7
> >
> > However, sometimes we are interested in the indexes of the elements where the
> > condition holds. Is there an easy way to transform the I vector into an
> > indexes vector similar to:  I == c(2,5,6) ?
> >
> > I know that I can traverse the I vector with a for() loop collecting the
> > indexes, I just wonder if such an operation can be avoided.
> >
> > Thanks,
> >
> >   -Sergio.
> >
> > ______________________________________________
> > 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.
> 
> 
> 
> --
> 
> Bert Gunter
> Genentech Nonclinical Biostatistics
> 
> Internal Contact Info:
> Phone: 467-7374
> Website:
> http://pharmadevelopment.roche.com/index/pdb/pdb-functional-groups/pdb-
> biostatistics/pdb-ncb-home.htm
> 
> ______________________________________________
> 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