I have a table (dt1
) of fairly regular time points, like this:
DATE TIME READING
2022-02-02 11:50:23 123.34
2022-02-02 11:50:59 125.66
2022-02-02 11:51:16 159.23
2022-02-02 11:52:34 234.22
etc... Note that the interval between time points can be very irregular.
I have another table (dt2
) specifying the start and end times of treatments:
DATE RED_START RED_END GREEN_START GREEN_END
2022-02-02 11:50:30 11:51:12 11:52:12 11:53:17
2022-02-02 11:54:10 11:55:09 11:56:30 11:57:15
It specifies when the treatment was "RED" and when it was "GREEN". Note that there are certain time periods that are neither "RED" or "GREEN".
I'm trying to add a column to the first table to say what the treatment was at the time point given for each row. The desired output would look like this:
DATE TIME READING TREATMENT
2022-02-02 11:50:23 123.34 NULL
2022-02-02 11:50:59 125.66 RED
2022-02-02 11:51:16 159.23 NULL
2022-02-02 11:52:34 234.22 GREEN
I've tried using a non-equi join between the two tables to generate helper columns. e.g.
dt1[, RED := c("TRUE","FALSE")[
dt2[.SD, on=.(DATE, RED_START<=TIME, RED_END>=TIME),
by=.EACHI]
]]
But I've not got the hang of the syntax and it's not working. I'm not sure if I'm stating the multiple conditions incorrectly, or if the non-equi join requires additional info. I would prefer answers using data.table
if possible, to keep it consistent with the rest of my code.