abbas786
abbas786

Reputation: 401

Adding a column based on another column R data.table

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))
dt2 <- data.table(Num = 1:5, Letter = c('A','B','C','D','E'))

I want to add a column to the first data table based on dt2, so it will have two columns:

dt1 <- dt1[,Letter := "THIS WILL CONTAIN AN 'A' FOR EVERY '1', 'B' FOR EVERY '2', ETC"]

The second data table serves as a key for which letter corresponds to which number in another data table.

Thanks.

Upvotes: 0

Views: 2042

Answers (3)

h3rm4n
h3rm4n

Reputation: 4187

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

Upvotes: 2

akrun
akrun

Reputation: 887851

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]]

Upvotes: 3

user3710546
user3710546

Reputation:

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

Upvotes: 4

Related Questions