From vincent.goulet at act.ulaval.ca  Sat Apr 12 19:30:13 2008
From: vincent.goulet at act.ulaval.ca (Vincent Goulet)
Date: Sat, 12 Apr 2008 13:30:13 -0400
Subject: [Rd] HOW TO AVOID LOOPS
In-Reply-To: <FC1A822CDEFB4DE38EB135F6BE851F55@your136f2019dc>
References: <FC1A822CDEFB4DE38EB135F6BE851F55@your136f2019dc>
Message-ID: <B57FC282-F852-432D-942F-458FA4E00ABB@act.ulaval.ca>

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



[Rd] HOW TO AVOID LOOPS
Vincent Goulet