2

I have two indexed data tables, and I want to add a column from one table to the other by index. My current approach is as follows:

A <- data.table(index = seq(6,10), a = rnorm(5))
B <- data.table(index = seq(10), b = rnorm(10))
setkey(B, index)
A[, b := B[.(A[,index]), b]]

While this gets the job done, the syntax seems a bit redundant. Is there a cleaner way to perform the same operation?

user3294195
  • 1,748
  • 1
  • 19
  • 36

1 Answers1

3

We can do this with a join

A[B, b := b, on = .(index)]

The setkey step is not needed here

akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks. How about if the `index` columns don't have the same name? For instance, assume `B` has index column `index1` instead. – user3294195 Aug 22 '18 at 03:49
  • 2
    @user3294195 In that case change the `on` to `on = .(index = index1)]` i.e. `A[B, b := b, on = .(index = index1)]` – akrun Aug 22 '18 at 03:50