[R] Turning a logical vector into its indices without losing its length
François Pinard
pinard at iro.umontreal.ca
Sat Aug 25 00:41:31 CEST 2007
[Leeds, Mark (IED)]
>I have the code below which gives me what I want for temp based on
>invec but I was wondering if there was a shorter way ( i.e :
>a one liner ) without having to initialize temp to zeros. This is
>ppurely for learning purposes. Thanks.
>invec <- 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
A mere:
invec * seq_along(invec)
would do it. To be honest, I dislike the multiplication trickery, and
so prefer Gabor's solution, even if a bit longer:
ifelse(invec, seq_along(invec), 0)
--
François Pinard http://pinard.progiciels-bpi.ca
More information about the R-help
mailing list