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

Gabor Grothendieck ggrothendieck at gmail.com
Fri Aug 24 23:24:31 CEST 2007


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))


>
>
> On 8/24/07, Leeds, Mark (IED) <Mark.Leeds at morganstanley.com> wrote:
> > I have the code below which gives me what I want for temp based on
> > logvec but I was wondering if there was a shorter way ( i.e :
> > a one liner ) without having to initialize temp to zeros.  This is
> > purely for learning purposes. Thanks.
> >
> > logvec <- c(TRUE,FALSE,FALSE,TRUE,FALSE,FALSE,TRUE,FALSE)
> >
> > temp<-numeric(length(invec))
> > temp[invec]<-which(invec)
> > temp
> >
> > [1] 1 0 0 4 0 0 7 0
> >
> > obviously, the code below doesn't work.
> >
> > temp <- which(invec)
> > > temp
> > [1] 1 4 7
> > --------------------------------------------------------
> >
> > This is not an offer (or solicitation of an offer) to buy/se...{{dropped}}
> >
> > ______________________________________________
> > R-help at stat.math.ethz.ch 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