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

From: jim holtman <jholtman_at_gmail.com>
Date: Tue, 19 Jun 2007 06:37:13 -0400

This should do it for you:

> x <- c( TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, FALSE, TRUE );
> y <- rle(x)
> unlist(lapply(seq(length(y$lengths)), function(.indx){

+     if (y$values[.indx]) seq(y$lengths[.indx])
+     else rep(0, y$lengths[.indx])
+ }))

[1] 1 2 3 0 0 1 2 0 1

On 6/19/07, Feng, Ken <ken.feng_at_citi.com> wrote:
>
> Hi,
>
> I start with an array of booleans:
>
> 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?
>
> Thanks in advance.
>
> - Ken
>
> ______________________________________________
> R-help_at_stat.math.ethz.ch 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.
>

-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?

	[[alternative HTML version deleted]]

______________________________________________
R-help_at_stat.math.ethz.ch 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.
Received on Tue 19 Jun 2007 - 10:44:29 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 19 Jun 2007 - 11:32:18 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.