I have the following dataset
structure(list(Time = c(0L, 0L, 0L, 0L, 0L, 200L, 200L, 200L,
200L, 200L, 400L, 400L, 400L, 400L, 400L), AgentID = c(1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), AC = c("c",
"c", "c", "c", "c", "c", "c", "c", "c", "c", "c", "c", "c", "c",
"c"), Layer = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L), Type = c("b", "b", "b", "b", "b", "b", "b", "b",
"b", "b", "b", "b", "b", "b", "b"), Data = c(0, 0, 0, 0, 0, 0.117073864,
0.13028602, 0.11111003, -0.11538354, 0.07852934, 0.24280901,
0.24271743, 0.21535376, -0.2213944, 0.23355752), SimulationID = c(4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L), discountFactor = c(0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), N = c(80L,
80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L,
80L)), row.names = c(NA, -15L), class = c("data.table", "data.frame"
), .internal.selfref = <pointer: 0x55843aed0a70>)
What I want to do is to group the rows with with on=.(Layer,Type,AC,AgentID,Time,SimulationID,N,discountFactor)
, and do nodeVelocity:=Data-oldData
where oldData
is the Data
column having oldTime=Time-200
.
I tried
d[d[,.(Time=Time+200,Data), by=.(Layer,Type,AC,AgentID,SimulationID,N,discountFactor)],
`:=` (nodeVelocity=x.Data-i.Data, iData=i.Data)
,on=.(Layer,Type,AC,AgentID,Time = Time,SimulationID,N,discountFactor)]
However, in the above code, as you can see from its iData
column, the subtraction is done via the last row of i.Data
(i.Data =: oldData). Why is this? I was expecting an element-wise vector substraction but what I got is vector minus the last row of the other vector.