Saturday, 4 February 2017

r - Join data tables including missing records in both of them




I want to join data tables:




> (d1 <- data.table(k=1:3,v=letters[1:3],key="k"))
k v
1: 1 a
2: 2 b
3: 3 c
> (d2 <- data.table(k=2:4,v=LETTERS[2:4],key="k"))
k v
1: 2 B
2: 3 C
3: 4 D

> d1[d2]
k v i.v
1: 2 b B
2: 3 c C
3: 4 NA D
> d2[d1]
k v i.v
1: 1 NA a
2: 2 B b
3: 3 C c



What I want is the "union" of the last two joins:



   k  v i.v
1: 1 NA a
2: 2 B b
3: 3 C c
4: 4 D NA



Thanks!


Answer



You can use merge:



merge(d2,d1,all=TRUE)

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...