[R] remove loop which compares row i to row i-1

David Winsemius dwinsemius at comcast.net
Tue Jul 17 06:43:54 CEST 2012


On Jul 16, 2012, at 10:27 AM, jcrosbie wrote:

> Thank you, That was very helpful.
>
> I do have another problem along the same lines. But I can not think  
> of a way
> to do this with  a function like ddply or aggregate.
>
> Example:
> x = sample(0:1,42,TRUE)
> [1] 1 1 1 1 0 1 0 0 1 1 1 1 1 0 0 0 1 0 0 1 1 0 0 0 0 1 1 0 0 0 1 0  
> 1 1 0 1
> 1 1 0 0 0 0

 > x <- scan()
1:  1 1 1 1 0 1 0 0 1 1 1 1 1 0 0 0 1 0 0 1 1 0 0 0 0 1 1 0 0 0 1 0 1  
1 0 1
37: 1 1 0 0 0 0
43:
Read 42 items
 > sx <- tapply(x, cumsum(x==0), FUN= function(z) sum(z) )
 > sx[sx>0]
  0  1  3  6  8 12 15 16 17
  4  1  5  1  2  2  1  2  3
 > unname(sx[sx>0])
[1] 4 1 5 1 2 2 1 2 3

> I want to find create a new vector such that the sums of the 1's  
> stops each
> time there is a 0 and starts again next time there is a one.
> Output would be:
> 4,1, 5, 1,2,2,1,2,3
>
>

David Winsemius, MD
today: Springdale, UT



More information about the R-help mailing list