[Rd] HOW TO AVOID LOOPS

Vincent Goulet vincent.goulet at act.ulaval.ca
Sat Apr 12 19:30:13 CEST 2008


Le sam. 12 avr. à 12:47, carlos martinez a écrit :
>> Looking for a simple, effective a minimum execution time solution.
>>
>> For a vector as:
>>
>> c(0,0,1,0,1,1,1,0,0,1,1,0,1,0,1,1,1,1,1,1)
>>
> To transform it to the following vector without using any loops:
>
>> (0,0,1,0,1,2,3,0,0,1,2,0,1,0,1,2,3,4,5,6)
>>
> Appreciate any suggetions.

This does it -- but it is admittedly ugly:

 > x <- c(0,0,1,0,1,1,1,0,0,1,1,0,1,0,1,1,1,1,1,1)
 > ind <- which(x == 0)
 > unlist(lapply(mapply(seq, ind, c(tail(ind, -1) - 1, length(x))),  
function(y) cumsum(x[y])))
  [1] 0 0 1 0 1 2 3 0 0 1 2 0 1 0 1 2 3 4 5 6

(The mapply() part is used to create the indexes of each sequence in x  
starting with a 0. The rest is then straightforward.)

HTH

---
   Vincent Goulet, Associate Professor
   École d'actuariat
   Université Laval, Québec
   Vincent.Goulet at act.ulaval.ca   http://vgoulet.act.ulaval.ca



More information about the R-devel mailing list