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
   [EMAIL PROTECTED]   http://vgoulet.act.ulaval.ca

______________________________________________
R-devel@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel

Reply via email to