Worked fine Gabor, thanks!

I just removed the init argument from the Reduce function and I got it
without the first 0.

Henrique

 
-----Mensagem original-----
De: Gabor Grothendieck [mailto:ggrothendi...@gmail.com] 
Enviada em: quinta-feira, 25 de novembro de 2010 22:13
Para: henrique
Cc: r-help@r-project.org
Assunto: Re: [R] Cumsum with a max and min value

On Thu, Nov 25, 2010 at 3:44 PM, henrique <henri...@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

______________________________________________
R-help@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.

Reply via email to