From: Stephen Milborrow <>
Date: Mon, 14 Apr 2008 22:22:51 +0200

> 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)

Here is a fast solution using the Ra just-in-time compiler

if (length(x) > 1)

    for (i in 2:length(x))

        if (x[i])
            x[i] <- x[i-1] + 1

The times in seconds for various solutions mailed to r-devel are listed below. There is some variation between runs and with the contents of x. The times shown are for

set.seed(1066); x <- as.double(runif(1e6) > .5)

This was tested on a WinXP 3 GHz Pentium D with Ra 1.0.7 (based on R 2.6.2). The code to generate these results is attached.

vin 24
greg 11
had 3.9
dan 1.4
dan2 1.4
jit 0.25 # code is shown above, 7 secs with standard R 2.6.2>

Stephen Milborrow mailing list
Received on Mon 14 Apr 2008 - 20:27:48 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 15 Apr 2008 - 00:31:10 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.

list of date sections of archive