0

I am generating a matrix of all combinations of 5 numbers taken 3 at a time, without replacement, like this:

v <- seq(1,5,1) 
combs <- t(combn(v,3))

Part of the output is as following:

    [,1]  [,2]  [,3]
[,1]    1   2   3
[,2]    1   2   4
[,3]    1   2   5
[,4]    1   3   4
[,5]    1   3   5
.
.
.

Now, I want to filter out all rows containing, for example, numbers 1 and 3, where the remaining element doesn't matter. How can this be done?

Thank you

BlueSea
  • 27
  • 4

1 Answers1

4

Here is one way using rowSums :

combs[rowSums(combs == 1) > 0 & rowSums(combs == 3) > 0, ]

#     [,1] [,2] [,3]
#[1,]    1    2    3
#[2,]    1    3    4
#[3,]    1    3    5

You can also use apply :

combs[apply(combs, 1, function(x) all(c(1, 3) %in% x)), ]
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • 1
    Slight variation to use `rowSums` with a vector - `combs[rowSums(replace(combs, , combs %in% c(1,3))) >= 2,]` – thelatemail Jan 07 '21 at 05:57