I can make calculations based on previous and current row in R.
In case of this dataframe(df):
A B
[1] 2 2
[2] 2 3
[3] 4 5.5
...
B2 = A2 + 0.5*B1
I can calculate this function by using this code.
for( i in 2:nrow(df) ) {
B[i] <- 1/2 * B[i-1] + df$A[i]
}
However, I have an Id(group) in my dataset, so I need to calculate this function by id.
id A B
[1] 1 0 0
[2] 1 2 2
[3] 1 2 3
[4] 2 1 1
[5] 2 4 4.5
[6] 2 4 6.25
...
B2 = A2 + 0.5*B1
B4 = A4 + 0.5*0 (becasue id is changed)
B5 = A5 + 0.5*B4
...
How can I handle this problem in R?
Thanks.
Since it seems like the result of each step depends on the previous one in the way you’re doing it now, getting rid of the
forloop appears tricky. I’m wondering if something like this is fast enough: