[R] Counting value changes

William Dunlap wdunlap at tibco.com
Sat Feb 18 21:33:05 CET 2012


> I made a small vector consisting of ones and zeros. 
> Something like this x <- c(0,1,0,1,0,0,1,0), and all I need is to count
> how many times "0" becomes "1".

Since x consists solely of 0's and 1's this is same as
  sum(diff(x)==1) # 3 in your example

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 Pete Brecknock
> Sent: Saturday, February 18, 2012 11:52 AM
> To: r-help at r-project.org
> Subject: Re: [R] Counting value changes
> 
> 
> maris478 wrote
> >
> > Good afternoon,
> > I've encountered a little bit of a problem, would appreciate any help
> > here.
> >
> > I made a small vector consisting of ones and zeros.
> > Something like this x <- c(0,1,0,1,0,0,1,0), and all I need is to count
> > how many times "0" becomes "1".
> > Tried various, of what I thought, methods with built in functions. Didn't
> > get any further.
> >
> > Thank you very much.
> >
> 
> How about ...
> 
> x <- c(0,1,0,1,0,0,0,0)
> 
> sum(rle(x)$values)
> 
> HTH
> 
> Pete
> 
> --
> View this message in context: http://r.789695.n4.nabble.com/Counting-value-changes-
> tp4400267p4400348.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> 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