There are two data tables of the following structure:
DT1 <- data.table(ID=c("A","B","C"), P0=c(1,10,100), key="ID")
DT2 <- data.table(ID=c("B","B","B","A","A","A","C","C","C"), t=rep(seq(0:2),3), P=c(NA,30,50,NA,4,6,NA,200,700))
In data tableDT2
all NAs in column P
shall be updated by values P0
out of data table DT1
.
If DT2
is ordered by ID
like DT1
, the problem can be solved like this:
setorder(DT2,ID)
idxr <- which(DT2[["t"]]==1)
set(DT2, i=idxr, j="P", value=DT1[["P0"]])
But how can the data tables be "merged" without ordering DT2
before?