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
.