Combinatorics and Probability

Asked

Viewed 27 times

4

When I combine for example 4 strings ["A","B","C","D"] 2 to 2, ie AB,AC,AD,BC... I can count on how many occurrences A and B appeared?

My problem involves 16 items that combined 4 to 4 generate 1820, but I would like to know how many of these 1820 items A and B, for example, appear together or isolated.

I already managed to generate the vector with combn and Combinations but I can’t count.

  • The combination is a vector product in which repeated letters are excluded from the final result. Then the solution is to create a vector from the square of the original vector (using a nested for loop, for example) and use a filter that eliminates repeated and has the letters of interest

1 answer

4

A solution may be the following.
Use the function to apply to each combination to obtain a logical vector if both (all) the letters are in each combination. Still use which to give a numerical vector, which without the results FALSE is shorter and easy to present as output.

AB <- LETTERS[1:2]
which(combn(LETTERS[1:16], 4, function(x) all(AB %in% x)))
# [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22
#[23] 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
#[45] 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
#[67] 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
#[89] 89 90 91

Browser other questions tagged

You are not signed in. Login or sign up in order to post.