help you fix your problem I have the following dataset, and I need to acumulate the value and sum, if the factor is 0, and then put the cummulated sum when I found the factor != 0. , If you want to stick with the for-loop, you can try this code :
Any of those help Your case is exactly the same as generating a AR(1) model with coefficient 0.5. You can use the filter function to generate the data. filter also support higher order recursion, convolution or mixture of them(think about the ARMA model). You may have a look ofconvolve for other convolutions. Also, you could compiler your code to speed up the loop. In my code, complied loop and uncompiled loop code is about 111 and 162 times slower than filter respectively.
for(i in 2:length(x))
out[i] <- out[i-1]*alpha+x[i]
FilterCustomCumsum<-function(x,alpha) as.numeric(filter(x,alpha, method = "recursive"))
# Test whether they are the same
identical(compiledCustomCumsum(x,0.5) , FilterCustomCumsum(x,0.5) )
test replications elapsed relative user.self sys.self user.child sys.child
2 compiledCustomCumsum 100 8.89 111.125 8.78 0.01 NA NA
1 CustomCumsum 100 13.02 162.750 11.84 0.50 NA NA
3 FilterCustomCumsum 100 0.08 1.000 0.08 0.00 NA NA
R Cumulative sum by factor with sum 'reset'
By : Geoff Chappell
Date : March 29 2020, 07:55 AM
will be helpful for those in need my problem is I'm trying to find the cumulative sum of rainfall by season (DJF, MAM, JJA, SON) and by year (1926 - 2000), with the sum resetting to zero at the end of each season. , May be you can try dplyr
this will help One way is to try the matrixStats::rowCummaxs function, but you will need to convert to a matrix first. Though, judging by your data structure, I would recommend working with a matrix instead of a data.frame in the first place