user3294195
user3294195

Reputation: 1828

Map entries between two data.tables

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

Answers (2)

Frank
Frank

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

akuiper
akuiper

Reputation: 214977

I think you need a join:

A[B, on = c("V1", "V2", "V3")]

#   V1 V2 V3 index
#1:  1  2  2     4
#2:  2  1  2     6
#3:  2  2  2     8

Upvotes: 1

Related Questions