# Re: [R] How do I avoid a loop?

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Tue, 19 Jun 2007 07:42:17 -0400

xx is 1 in every position of the first run of TRUE, 2 in every position in the 2nd run of TRUE and so on. The parenthesized expression in the second line converts those to increasing values and multiplying it by x zaps the garbage in the positions that correspond to FALSE in x.

xx <- cumsum(diff(c(FALSE, x)) > 0)
(seq_along(x) - match(xx, xx) + 1) * x

On 6/19/07, Feng, Ken <ken.feng_at_citi.com> wrote:
> Hi,
>
>
> x <- c( TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, FALSE, TRUE );
>
> I want to define an y <- f(x) such that:
>
> y <- c( 1, 2, 3, 0, 0, 1, 2, 0, 1 );
>
> In other words, do a cumsum when I see a TRUE, but reset to 0 if I see a FALSE.
>
> I know I can do this with a very slow and ugly loop or maybe use apply,
> but I was hoping there are some R experts out there who can show me
> a cleaner/more elegant solution?
>
>
> - Ken
>
> ______________________________________________
> R-help_at_stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help