I have two data tables in R:
#install.packages(\"data.table\")
library(data.table)
dt1 <- data.table(Num = c(1,1,1,2,2,2,2,3,3,3,3,3,3,4,4,4,4,4,4,4,5,5,5
We can join with using on
library(data.table)#v1.9.6+
dt2[dt1, on ="Num"]
For creating the "Letter" column in "dt1", we don't need the "dt2"
dt1[, Letter:= LETTERS[Num]]
setkey(dt1, Num)
setkey(dt2, Num)
dt2[dt1]
Num Letter
1: 1 A
2: 1 A
3: 1 A
4: 2 B
5: 2 B
The disadvantage of the methods in the other answers is that dt1 is not updated and the result is only printed to the console. You can update dt1 by reference as follows:
dt1[dt2, lttr := Letter, on="Num"]
This gives the following result:
> dt1
Num lttr
1: 1 A
2: 1 A
3: 1 A
4: 2 B
5: 2 B
6: 2 B
7: 2 B
8: 3 C
9: 3 C
10: 3 C
11: 3 C
12: 3 C
13: 3 C
14: 4 D
15: 4 D
16: 4 D
17: 4 D
18: 4 D
19: 4 D
20: 4 D
21: 5 E
22: 5 E
23: 5 E