# [R] Cumsum with a max and min value

jim holtman jholtman at gmail.com
Fri Nov 26 03:07:19 CET 2010

```Does this do it;

> pmin(2, pmax(-2, cumsum(a)))
[1]  0  1  1  2  2  2  1  0  0 -1 -2

On Thu, Nov 25, 2010 at 3:44 PM, henrique <henrique at allianceasset.com.br> wrote:
> I have a vector of values -1, 0, 1, say
>
>
>
> a <- c(0, 1, 0, 1, 1, -1, -1, -1, 0, -1, -1)
>
>
>
> I want to create a vector of the cumulative sum of this, but I need to set a
> maximum and minimum value for the cumsum, for example:
>
>
>
> max_value <- 2
>
> min_value <- -2
>
>
>
> the expected result would be (0, 1, 1, 2, 2, 1, 0, -1, -1, -2, -2)
>
>
>
> The only way I managed to do It, was
>
>
>
> res <- vector(length=length(a))
>
> res[1] <- a[1]
>
> for ( i in 2:length(a)) res[i] <- res[i-1] + a[i] * (( res[i-1] < max_value
> & a[i] > 0 ) | ( res[i-1] > min_value & a[i] < 0 ))
>
>
>
>
>
> This is certainly not the best way to do it, so any suggestions?
>
>
>
>
>
> Henrique
>
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

--
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?

```

More information about the R-help mailing list