Find combinations of rows grouped by a column, picking TWO ROWS from each group in data.frame in R

Viewed 32

Essentially this problem, but picking 2 rows from each group.

In the scenario here, each group has 2+ rows, and I need to generate all combinations where I select two of them. Columns contain group, unique IDs, and numerical values.

Example data:

dat <- data.frame(Group = c("A","A","A","B","B","C","C","C","D","D","D","D")) %>%
  group_by(Group) %>%
  mutate(ID = paste(Group, seq_along(Group), sep ="_")) %>%
  ungroup() %>%
  mutate(value = sample(1:length(ID), replace=TRUE))

How do I find all possible data.frame combinations where n = 2 rows of each group are chosen?

Desired output could be a single list/data.frame of those combinations with unique IDs as in the answer to the linked question above, or preferably, a list of the unique data.frames themselves - each containing the 2 rows per group and their Group, ID, and value columns.

Thank you for your help!

0 Answers
Related