[R] RES: Cumsum with a max and min value

henrique henrique at allianceasset.com.br
Fri Nov 26 13:36:52 CET 2010


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:ggrothendieck at gmail.com] 
Enviada em: quinta-feira, 25 de novembro de 2010 22:13
Para: henrique
Cc: r-help at r-project.org
Assunto: Re: [R] Cumsum with a max and min value

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