1

I have the following function. I really dislike the fact that I am expressing it in the form of a for loop. Would it be possible to express it using an apply function ?

Note that x is just a vector as below.

c(0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, -1, -1, 1, -1, 0, 0, 0, 0, -1, 0, -1, -1, 0, 0, 0, 0, 1, 0, -1, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, -1, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0)

testing <- function(x){
  x_cumsum <- 0
  for(i in 1:length(x)){
    x_cumsum = x_cumsum + x[i]
    if(x_cumsum < 0){
      x_cumsum = 0
    }    
  }
  return(x_cumsum)
}

Please note that this is kind of similar to cumsum function but there is a condition that resets x_cumsum to 0 whenever it is smaller than 0.

mynameisJEFF
  • 4,073
  • 9
  • 50
  • 96
  • Instead of `apply` why not use the built-in function `cumsum` ? – G5W Jun 17 '18 at 16:40
  • there is a condition in there, which resets the `x_cumsum` to 0. That's why i cannot use `cumsum` – mynameisJEFF Jun 17 '18 at 16:41
  • 1
    [Cumulative Sum with Conditions in R](https://stackoverflow.com/questions/40996306/cumulative-sum-with-conditions-in-r); [Conditional cumsum with reset](https://stackoverflow.com/questions/34531568/conditional-cumsum-with-reset), and links therein. – Henrik Jun 17 '18 at 16:49
  • [Cumulative sum until maximum reached, then repeat from zero in the next row](https://stackoverflow.com/questions/15466880/cumulative-sum-until-maximum-reached-then-repeat-from-zero-in-the-next-row?noredirect=1&lq=1) – Henrik Jun 17 '18 at 16:54

1 Answers1

0

Try this:

x_cumsum<-0;
lapply(x,function(y) x_cumsum<-max(0,x_cumsum+y))
# 0 for your sample input.
Rohit
  • 1,967
  • 1
  • 12
  • 15