Suppose I have two data tables:
X <- data.table(id = 1:5, L = letters[1:5])
id L
1: 1 a
2: 2 b
3: 3 c
4: 4 d
5: 5 e
Y <- data.table(id = 3:5, L = c(NA, "g", "h"), N = c(10, NA, 12))
id L N
1: 3 NA 10
2: 4 g NA
3: 5 h 12
Would it be possible to do a left outer join of X
and Y
by id
using data table built-in functions? If not, I would like build a function (e.g. leftOuterJoin
) with the following expected output:
leftOuterJoin(X, Y, on = "id")
id L N
1: 1 a NA
2: 2 b NA
3: 3 NA 10
4: 4 g NA
5: 5 h 12
I have tried without success:
X[Y, on = "id"]
id L i.L N
1: 3 c NA 10
2: 4 d g NA
3: 5 e h 12
I have also tried this, which is almost what I am looking for:
setkey(X, id)
setkey(Y, id)
merge(X, Y, all.x = TRUE)
id L.x L.y N
1: 1 a NA NA
2: 2 b NA NA
3: 3 c NA 10
4: 4 d g NA
5: 5 e h 12
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…