I am trying to solve the problem proposed here. Basically what I need is, for each row of the data.table, take the values of each variable in the previous row and use them to define the variable values in the following row.
I have tried using data.table
, but the result is quite bulky and I believe extremely inefficient (especially for a big number of rows). I also tried using the shift()
function, but could not fit it in my temporary solution.
Here is a toy example:
library(data.table)
DT = data.table(a = numeric(10L), b = numeric(10L), c = numeric(10L), iter = 1:10)
for(i in DT[,.I]){
DT[i, c('a','b','c') := {
if(iter == 1) {
a = 1
b = 2
c = 3
} else { # if it is not the first iteration
a = DT[i-1, a + b] # read the values from the previous row to compute the new values
b = DT[i-1, b] - a
c = a / b + DT[i-1, c]
}
.(a, b, c)
}]
}
and here's the output:
a b c iter
1: 1 2 3.0000000 1
2: 3 -1 0.0000000 2
3: 2 -3 -0.6666667 3
4: -1 -2 -0.1666667 4
5: -3 1 -3.1666667 5
6: -2 3 -3.8333333 6
7: 1 2 -3.3333333 7
8: 3 -1 -6.3333333 8
9: 2 -3 -7.0000000 9
10: -1 -2 -6.5000000 10
Can someone help me improve the code?