I am trying to add new columns to data.table
, where the values ββin the rows depend on the relative relationship of the values ββin the row. To be more precise, if there is an X value in a row, I would like to know how many other values ββare in the same column (and group) that are inside the X-30.
That is, given this:
DT<-data.table( X = c(1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 1, 1), Y = c(100, 101, 133, 134, 150, 156, 190, 200, 201, 230, 233, 234), Z = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))
I would like to get a new column with values:
N <- c(0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 2)
I tried the following, but I am not getting the results that I could use:
DT[,list(Y,num=cumsum(Y[-.I]>DT[.I,Y]-30),Z),by=.(X)]
Any ideas how to do this?