0

Assume we have a datatable DT with multiple rows and columns

DT <- data.table(c1=1:10, c2=11:20, C3=21:30)

and we have

a <- c(1,5,7)
b <- c(2,3,1)

Is there an easy way to generate a pair-wise combination of a and b and get the following items?

DT[1,2]
DT[5,3]
DT[7,1]

i.e., I expect to get

11, 25, 7

DT[a,b] returns a 3x3 datatable which is not what I am looking for.

Mahmoud
  • 381
  • 4
  • 12
  • Need code for DT. Also nee you to specify what you expect since `[.data.table` does not behave like `[.data.frame` – IRTFM Mar 05 '19 at 00:48
  • Added a sample DT! – Mahmoud Mar 05 '19 at 00:53
  • 1
    Outside of `data.table`, you can use matrix indexing, which is very quick - `as.data.frame(DT)[cbind(a,b)]` – thelatemail Mar 05 '19 at 00:53
  • DT[ cbind(a,b) ] worked for me. Thanks! – Mahmoud Mar 05 '19 at 00:59
  • 1
    @Mahmoud - it shouldn't, as that code won't work on a `data.table`. But I think for this particular operation, a `data.table` is not very well suited. – thelatemail Mar 05 '19 at 01:00
  • It's actually going to be faster to not coerce and just use `[.data.frame`. I added another answer to the cited duplicate question which instead coerce to matrix (which would be even more dangerous.) – IRTFM Mar 05 '19 at 01:03

0 Answers0