Bill Dunlap Spotfire, TIBCO Software wdunlap tibco.com
> -----Original Message----- > From: r-help-boun...@r-project.org > [mailto:r-help-boun...@r-project.org] On Behalf Of speretti > Sent: Wednesday, May 26, 2010 10:22 AM > To: r-help@r-project.org > Subject: [R] counts of a vector > > > Hi, > > I need help to find an efficient way to transform a vector like: > > a<-c(1,1,0,1,0,0,0,1,1,1,1,0,1,0,1,1) > > in a vector that counts only di 1 elements, like: > > b<-c(1,2,0,1,0,0,0,1,2,3,4,0,1,0,1,2) The following is pretty quick: > f <- function (x) { # x must be entirely composed of 0's and 1's or FALSE's and TRUE's. csx <- cumsum(x) csx - cummax(csx * (1-x)) # 1-x could also be !x } > all.equal(f(a), b) [1] TRUE Bill Dunlap Spotfire, TIBCO Software wdunlap tibco.com > > > Thank you! > -- > View this message in context: > http://r.789695.n4.nabble.com/counts-of-a-vector-tp2232047p223 2047.html > Sent from the R help mailing list archive at Nabble.com. > > ______________________________________________ > R-help@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. > ______________________________________________ R-help@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.