Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cumulative sum for positive numbers only [duplicate]

Tags:

r

I have this vector :

x = c(1,1,1,1,1,0,1,0,0,0,1,1) 

And I want to do a cumulative sum for the positive numbers only. I should have the following vector in return:

xc = (1,2,3,4,5,0,1,0,0,0,1,2) 

How could I do it?

I've tried : cumsum(x) but that do the cumulative sum for all values and gives :

cumsum(x) [1] 1 2 3 4 5 5 6 6 6 6 7 8 
like image 651
Math Avatar asked Feb 03 '15 09:02

Math


People also ask

What is cumulative sum example?

The definition of the cumulative sum is the sum of a given sequence that is increasing or getting bigger with more additions. The real example of a cumulative sum is the increasing amount of water in a swing pool. Example: Input: 10, 15, 20, 25, 30. Output: 10, 25, 45, 70, 100.

How do you find the cumulative sum in Python?

Python numpy cumsum() syntax The axis parameter defines the axis along which the cumulative sum is calculated. If the axis is not provided then the array is flattened and the cumulative sum is calculated for the result array. The dtype parameter defines the output data type, such as float and int.


2 Answers

One option is

x1 <- inverse.rle(within.list(rle(x), values[!!values] <-                    (cumsum(values))[!!values])) x[x1!=0] <- ave(x[x1!=0], x1[x1!=0], FUN=seq_along) x #[1] 1 2 3 4 5 0 1 0 0 0 1 2 

Or a one-line code would be

 x[x>0] <-  with(rle(x), sequence(lengths[!!values]))  x  #[1] 1 2 3 4 5 0 1 0 0 0 1 2 
like image 81
akrun Avatar answered Sep 17 '22 15:09

akrun


Here's a possible solution using data.table v >= 1.9.5 and its new rleid funciton

library(data.table) as.data.table(x)[, cumsum(x), rleid(x)]$V1 ## [1] 1 2 3 4 5 0 1 0 0 0 1 2 
like image 37
David Arenburg Avatar answered Sep 17 '22 15:09

David Arenburg