How to merge lists of vectors based on one vector belonging to another vector?

Viewed 154

In R, I have two data frames that contain list columns

d1 <- data.table(
  group_id1=1:4
)
d1$Cat_grouped <- list(letters[1:2],letters[3:2],letters[3:6],letters[11:12] )

And

d_grouped <- data.table(
  group_id2=1:4
)
d_grouped$Cat_grouped <- list(letters[1:5],letters[6:10],letters[1:2],letters[1] )

I would like to merge these two data.tables based on the vectors in d1$Cat_grouped being contained in the vectors in d_grouped$Cat_grouped

To be more precise, there could be two matching criteria:

a) all elements of each vector of d1$Cat_grouped must be in the matched vector of d_grouped$Cat_grouped

Resulting in the following match:

result_a <- data.table(
   group_id1=c(1,2)
   group_id2=c(1,1)
)

b) at least one of the elements in each vector of d1$Cat_grouped must be in the matched vector of d_grouped$Cat_grouped

Resulting in the following match:

result_b <- data.table(
  group_id1=c(1,2,3,3),
  group_id2=c(1,1,1,2)
)

How can I implement a) or b) ? Preferably in a data.table way.

EDIT1: added the expected results of a) and b)

EDIT2: added more groups to d_grouped, so grouping variables overlap. This breaks some of the proposed solutions

3 Answers
Related