# [R] conditional increase by increment

William Dunlap wdunlap at tibco.com
Wed Jul 18 22:48:56 CEST 2012

```> land<-c(0,0,0,0,1,1,1,0,0,0,1,1,0,0,0,0)
> expect <- c(1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3)
> cumsum(c(TRUE, diff(land)==1))
[1] 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3 3
> all.equal(.Last.value, expect)
[1] TRUE

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 penguins
> Sent: Wednesday, July 18, 2012 10:13 AM
> To: r-help at r-project.org
> Subject: [R] conditional increase by increment
>
> I am trying to assign increasing trip numbers to a binary variable ("land";
> 1=home and 0=away) where a string of 1's shouldn't increment the trip_no
> more than once.
>
> For example; based on
> land<-c(0,0,0,0,1,1,1,0,0,0,1,1,0,0,0,0)
> the "trip_no" sequence produced should be   1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3
>
> This is as far as I can get but Im stumped. In addition I need it to work on
> data where the land variable can start on "0" or "1" for trip_no=1. Any help
> would be hugely appreciated:
>
> land<-c(0,0,0,0,1,1,1,0,0,0,1,1,0,0,0,0)
> trip_no <- rep(0, length(land))
> gg<-cbind(land,trip_no)
>
> increment <- function(x){
>   eval.parent(substitute(x <- x + 1))
> }
>
>     for(i in length(gg)){
>       if(gg\$land[[i]]==1) {
>           gg\$trip_no<-increment(trip_no[i])
>         }
>      }
>
> --
> View this message in context: http://r.789695.n4.nabble.com/conditional-increase-
> by-increment-tp4636910.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