Try this:

ac <- cumsum(a)
ifelse(ac > 2, max_value, ifelse(ac < -2, min_value, ac))


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



-- 
Henrique Dallazuanna
Curitiba-Paraná-Brasil
25° 25' 40" S 49° 16' 22" O

	[[alternative HTML version deleted]]

