Is there a way to use previously value of .y in accumulate2 function in R?

38 Views Asked by At

I use the accumulate2 function with two arguments .x and .y and if/else statement.

.y (Volume) is a vector of periodic values that increases, then resets to a specific value (Vres, constant), and then starts increasing again. Intervals between resetting and max values for each period are different.

.x (Concentration) should follow a pattern of .y and accumulate while .y increases and then resets in the same moment as .y resets. I can implement it using an if/else statement with the condition if Volume != Vres, ..1 + ..2, else reset. But my problem is that it should reset to a specific value which depends on .y value BEFORE resetting (max increase before resetting).

Is there any way to extract the .y value for the previous iteration? Or we only can operate with previous values of .x? I tried lag(..3), but it doesn't work inside of accumulate2.

I have the following code:

time = c(tmin:tmax)
Concentration_in = c(0, rep(Concentration_in, length(time)-1))
C = accumulate2(Concentration_in[-1], Volume[-1],
                ~if(..3 != Vres) ..1 + ..2 else  ..1*Vres/..3,
                .init = first(Concentration_in))
)

But for else statement I would like to have instead of ..1*Vres/..3 previous value of ..3 like ..1*Vres/lag(..3)

In this example, I'm using a simple constant accumulation for Concentration, but this is not always the case in my task. Thank you very much in advance for any suggestions!

0

There are 0 best solutions below