Say we have two tables, each with a group indicator common between the two. Then for every row in DT1 we want to randomly select 2 rows from DT2 within each group.
One possible way to address this would be to randomly generate an integer column in DT2 that would coincide with the rows of DT1, and join the two tables together. But the number of rows varies by group and it's not clear how we could condition on this length by group.
Minimum working example:
DT1 <- data.table(var1=seq(1:20),
group=c(1,1,1,1,1,2,2,2,2,3,3,3,4,4,4,4,4,4,4,4))
DT2 <- data.table(obs=seq(1:13),
group=c(1,1,1,2,2,2,3,3,3,4,4,4,5))
View:
DT1
var1 group
1: 1 1
2: 2 1
3: 3 1
4: 4 1
5: 5 1
6: 6 2
7: 7 2
8: 8 2
9: 9 2
10: 10 3
11: 11 3
12: 12 3
13: 13 4
14: 14 4
15: 15 4
16: 16 4
17: 17 4
18: 18 4
19: 19 4
20: 20 4
DT2
obs group
1: 1 1
2: 2 1
3: 3 1
4: 4 2
5: 5 2
6: 6 2
7: 7 3
8: 8 3
9: 9 3
10: 10 4
11: 11 4
12: 12 4
13: 13 5
So for every row in DT1, I would like to pair it with 2 randomly selected rows from DT2 by group. The expected result might look something like:
DT3
var1 group obs
1: 1 1 1
2: 1 1 3
3: 2 1 2
4: 2 1 3
...
37: 19 4 10
38: 19 4 11
39: 20 4 10
40: 20 4 12
In case it needs to be said, the actual application has 400 million rows in DT1 and 10 million in DT2.