Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map entries between two data.tables

Tags:

r

data.table

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.

like image 600
user3294195 Avatar asked Jun 03 '26 21:06

user3294195


1 Answers

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

like image 157
Frank Avatar answered Jun 07 '26 15:06

Frank



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!