Suppose we have a data table like this:
DT <- data.table(x = 1:5, y = c(6, NA, 8, NA, 10), z = 11:15)
> DT
x y z
1: 1 6 11
2: 2 NA 12
3: 3 8 13
4: 4 NA 14
5: 5 10 15
x y z
1: 1 6 11
2: 2 11 12
3: 3 8 13
4: 4 13 14
5: 5 10 15
DT[is.na(y), `:=`(y = DT[5, z])]
DT[is.na(y), `:=`(y = DT[row-1, z])]
You can use replace
and shift
, i.e.
library(data.table)
DT[, y := replace(y, is.na(y), shift(z, type = 'lag')[is.na(y)])][]
which gives,
x y z 1: 1 6 11 2: 2 11 12 3: 3 8 13 4: 4 13 14 5: 5 10 15
We can avoid replace
as per @Jaap's comment as follows,
DT[is.na(y), y := DT[, shift(z, type = 'lag')[is.na(y)]]][]