Home > Enterprise >  Combinatorics in R
Combinatorics in R

Time:03-11

I have 4 items and I can peak 3 of them at random.But how can I calculate in R the total combinations?

I think it might be:

sample(4,3)

for one sample.But each time to run the sample function and if the results are the same or included in the previous results to be excluded and run it again until all the possible combinations occurs.

But how this can be done in R ?

CodePudding user response:

You can use combn to get all possible combinations:

combn(4, 3)

     [,1] [,2] [,3] [,4]
[1,]    1    1    1    2
[2,]    2    2    3    3
[3,]    3    4    4    4

For permutations, you can use, e.g., gtools::permutations:

gtools::permutations(4, 3)

     [,1] [,2] [,3]
 [1,]    1    2    3
 [2,]    1    2    4
 [3,]    1    3    2
 [4,]    1    3    4
 [5,]    1    4    2
 [6,]    1    4    3
 [7,]    2    1    3
 [8,]    2    1    4
 [9,]    2    3    1
[10,]    2    3    4
[11,]    2    4    1
[12,]    2    4    3
[13,]    3    1    2
[14,]    3    1    4
[15,]    3    2    1
[16,]    3    2    4
[17,]    3    4    1
[18,]    3    4    2
[19,]    4    1    2
[20,]    4    1    3
[21,]    4    2    1
[22,]    4    2    3
[23,]    4    3    1
[24,]    4    3    2
  • Related