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]]
______________________________________________
[email protected] 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.