Your expected results are not consistent to base R merge.
You expect to get LEFT OUTER JOIN while R base is designed to perform RIGHT OUTER JOIN.
Solution is just to swap tables.
library(data.table)
dt<-data.table(col1=c(0,1,2),col2=c("a","b","c"),col3=c("aa","ab","cc"))
dt1<-data.table(a=c(1,2))
dt1[dt, .(a = x.a, col1, col2, col3), on = c("a"="col1")]
# a col1 col2 col3
#1: NA 0 a aa
#2: 1 1 b ab
#3: 2 2 c cc
Additionally, you have to explicitly ask for x.a
column, also due to R base consistency on that matter.
The x.col
notation in j
was recently implemented in data.table 1.9.7 version. You can install it by
install.packages("data.table", type = "source",
repos = "https://Rdatatable.github.io/data.table")
But if you don't care on updating your dt
object then it is more efficient to use @eddi answer which adds column by reference.