Rgray
Rgray

Reputation: 23

Creating result groups in R, using each element once (combination without repetition)

I have a dataset of 6 individuals: A,B,C,D,E,F

I want to group these into two groups of three individuals and have done so with the combn function in R:

m <- combn(n, 3)

This gives me all 20 possible groups where individuals occur in multiple groups. From this set of groups I then went to find all possible combinations of results, where each individual can only be used once.

I would like to do this using combinations without repetition: C(n,r) = n! / r!(n-r)! and would therefore get 10 results that would look like this:

I am not sure how to code this in R, from the list of groups that I have generated.

Edit: to generate the dataset I am using I have used the following code:

individuals <- c("a","b","c","d","e","f")
n <- length(individuals)
x <- 3
comb = function(n, x) {
  factorial(n) / factorial(n-x) / factorial(x)
}
comb(n,x)
(m <- combn(n, 3)) 
numbers <- m
letters <- individuals
for (i in 1:length(numbers)) {
  m[i] <- letters[numbers[i]]
}

Upvotes: 2

Views: 69

Answers (1)

Ma&#235;l
Ma&#235;l

Reputation: 52209

In base R:

  1. Create combnations of 3 letters and store it in a list (asplit)
  2. Create new combnations of 2 groups (of 3 letters)
  3. Filter the list to only keep combinations where the both parts have no element in common
individuals <- c("a","b","c","d","e","f")
combn(individuals, 3, simplify = FALSE) |>
  combn(m = 2, simplify = FALSE) |>
  Filter(f = \(x) !any(x[[1]] %in% x[[2]]))

output

[[1]]
[[1]][[1]]
[1] "a" "b" "c"

[[1]][[2]]
[1] "d" "e" "f"


[[2]]
[[2]][[1]]
[1] "a" "b" "d"

[[2]][[2]]
[1] "c" "e" "f"


[[3]]
[[3]][[1]]
[1] "a" "b" "e"

[[3]][[2]]
[1] "c" "d" "f"


[[4]]
[[4]][[1]]
[1] "a" "b" "f"

[[4]][[2]]
[1] "c" "d" "e"


[[5]]
[[5]][[1]]
[1] "a" "c" "d"

[[5]][[2]]
[1] "b" "e" "f"


[[6]]
[[6]][[1]]
[1] "a" "c" "e"

[[6]][[2]]
[1] "b" "d" "f"


[[7]]
[[7]][[1]]
[1] "a" "c" "f"

[[7]][[2]]
[1] "b" "d" "e"


[[8]]
[[8]][[1]]
[1] "a" "d" "e"

[[8]][[2]]
[1] "b" "c" "f"


[[9]]
[[9]][[1]]
[1] "a" "d" "f"

[[9]][[2]]
[1] "b" "c" "e"


[[10]]
[[10]][[1]]
[1] "a" "e" "f"

[[10]][[2]]
[1] "b" "c" "d"

Upvotes: 1

Related Questions