[R] Cumsum with a max and min value
Gabor Grothendieck
ggrothendieck at gmail.com
Fri Nov 26 01:12:56 CET 2010
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)
>
Try this:
f <- function(x, y) max(min(x + y, max_value), min_value)
Reduce(f, a, 0, accumulate = TRUE)[-1]
--
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com
More information about the R-help
mailing list