Home > Mobile >  Combination with all data in group
Combination with all data in group

Time:04-10

I want to make 5 data into 3 groups with the condition that all data is in a group. Suppose the data I have (A, B, C, D, E). Then the possible combinations to be made into 3 groups are as follows.

enter image description here

CodePudding user response:

Perhaps not the smartest approach, but you could use

library(dplyr)
library(stringr)

combn(LETTERS[1:5], 3) %>% 
  t() %>% 
  data.frame() %>% 
  mutate(G1 = str_remove_all("ABCDE", paste(X1, X2, X3, sep = "|")), .before = 1) %>% 
  select(G1, G2 = X1, G3 = X2, G4 = X3)

This returns

   G1 G2 G3 G4
1  DE  A  B  C
2  CE  A  B  D
3  CD  A  B  E
4  BE  A  C  D
5  BD  A  C  E
6  BC  A  D  E
7  AE  B  C  D
8  AD  B  C  E
9  AC  B  D  E
10 AB  C  D  E

CodePudding user response:

Using combn.

res <- lapply(2:3, \(m, d) {
  cb <- t(combn(LETTERS[1:5], m))
  if (m == 2) {
    apply(cb, 1, paste, collapse='')
  } else {
    cb[order(-seq_len(choose(5, m))), ]
  }
  }) |> do.call(what=cbind) |> as.data.frame()
res
#      [,1] [,2] [,3] [,4]
#  [1,] "AB" "A"  "B"  "C" 
#  [2,] "AC" "A"  "B"  "D" 
#  [3,] "AD" "A"  "B"  "E" 
#  [4,] "AE" "A"  "C"  "D" 
#  [5,] "BC" "A"  "C"  "E" 
#  [6,] "BD" "A"  "D"  "E" 
#  [7,] "BE" "B"  "C"  "D" 
#  [8,] "CD" "B"  "C"  "E" 
#  [9,] "CE" "B"  "D"  "E" 
# [10,] "DE" "C"  "D"  "E" 
  • Related