Reputation: 1828
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.
Upvotes: 3
Views: 87
Reputation: 66819
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
Upvotes: 3