[R] Turning a logical vector into its indices without losing its length

Gabor Grothendieck ggrothendieck at gmail.com
Sat Aug 25 04:38:29 CEST 2007


On 8/24/07, Gabor Grothendieck <ggrothendieck at gmail.com> wrote:
> On 8/24/07, Gabor Grothendieck <ggrothendieck at gmail.com> wrote:
> > Here are two solutions:
> >
> > > logvec <- c(TRUE,FALSE,FALSE,TRUE,FALSE,FALSE,TRUE,FALSE)
> >
> > > ifelse(logvec, seq_along(logvec), 0)
> > [1] 1 0 0 4 0 0 7 0
> >
> > > replace(logvec * 0, logvec, which(logvec))
> > [1] 1 0 0 4 0 0 7 0
>
> Actually the * 0 is not needed.  The last one could simply be:
>
> replace(logvec, logvec, which(logvec))

If logvec can have NAs then this solution would not work but could
be modified to be done like this:

replace(logvec, which(logvec), which(logvec))



More information about the R-help mailing list