Since I can't find an answer in below questions:
Apply a recursive function over groups and rows without explicit for loop
How do I mimic the drag functionality for new rows such as in Excel but for R?
I'll try in asking a new question related to above. I.e, I want to apply a custom function recursively based on the output of previous values to the current row by group.
Example with a dataframe and a for loop:
for(i in 2:nrow(df1)) df1$z[i] <- df1$z[i-1] + df1$x[i-1] - df1$y[i-1]
Example with a dataframe and a for loop with custom function:
for(i in 2:nrow(df1)) df1$z[i] <- ifelse(df1$z[i-1] == df1$z[i],
df1$z[i-1] + df1$x[i-1] - df1$y[i-1],
df1$z[i-1] - df1$x[i-1] - df1$y[i-1])
However, with >1 mill rows, data.frames and for-loops are not optimal.
Is there any way to do above with data.table
or dtplyr
and optimized but also group-wise?
EDIT: See visualization of question.
It should first initiate from 2nd row like in for(i in 2:nrow(df)
and it should use the custom function if and only if group[i]==group[i-1]