[R] How do I avoid a loop?

Martin Becker martin.becker at mx.uni-saarland.de
Tue Jun 19 15:42:00 CEST 2007


Gabor Grothendieck wrote:
> 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
>
>
>   

If speed is a critical issue, there is another possibility. Thanks to 
Oleg Sklyar's "inline"-package, embedding C code is now quite easy:

library(inline)
code <- readLines(textConnection("
 SEXP res;
 PROTECT(res=allocVector(INTSXP,LENGTH(a)));
 int i,j=0;
 int *result = INTEGER(res);
 int *input  = INTEGER(a);
 for (i=0;i<LENGTH(a);i++) {
   if (input[i]) j = j+1; else j = 0;
   result[i] = j;
 }
 UNPROTECT(1);
 return res;
"))
myfastfunc <- cfunction(signature(a="logical"), code)

This solution is about ten times faster than Gabor's on my machine (time 
to compile the C code excluded!).

Regards,

  Martin

> 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.
>>
>>     
>
> ______________________________________________
> 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.
>



More information about the R-help mailing list