I have a data.table as so:
library(data.table)
dt.tst <- CJ(Type = c("A", "B"),
Range_val = seq(0,20000, by = 1000))
dt.tst[Range_val == 2000 & Type == "A", Value := 0.987]
dt.tst[Range_val == 2000 & Type == "B", Value := 1.987]
dt.tst[Range_val == 9000 & Type == "A", Value := 1.056]
dt.tst[Range_val == 9000 & Type == "B", Value := 2.138]
dt.tst[Range_val == 16000 & Type == "A", Value := 1.563]
dt.tst[Range_val == 16000 & Type == "B", Value := 2.089]
I would like to fill the NA:s in the Value-column:
- With the closest non-na-value by the Range_val-column and Type.
- In case of a tie the highest Range_val and it's corresponding Value should be used (but this is not a deal-breaker, speed is more important).
I could do this pretty simple but slow with a for-loop. So I would like a more clean way of doing this (and faster). What would be a good data.table-way of doing this?
There will always be non-na-values but the intervals might differ.