Suppose I have a data table A containing a set of entries and an index column that assigns a unique number to each row. I also have a data table B that contains entries of A, like so:
library(data.table)
set.seed(1)
A <- do.call(CJ, list(seq(3), seq(2), seq(2)))
A[,index := seq(nrow(A))]
B <- data.table(sample(3,3,replace=TRUE), sample(2,3,replace=TRUE),
sample(2,3,replace=TRUE))
I want to define an index column for B that assigns each row to the corresponding index in A. What is the most efficient way to do this with data.table?
Thanks.
To add a column from A to B based on their matching rows:
B[A, on=names(B), index := i.index ]
The main docs are at ?data.table
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With