Search code examples
rpython-3.xsamplesampling

Sample n objects x times according to a condition


I want to sample 6 letters from the total set of 26 n times so that each letter gets sampled exactly 3 times across all n times. How would I write this in R or python?

EDIT: I missed out one crucial criterion, each set of 6 letters should be unique. So each set of 6 letters should be sampled without replacement.


Solution

  • With your conditions you can have a maximum of 13 samples i.e. 26 * 3 / 6 = 13. Here's one way to get them -

    set.seed(2)
    m <- matrix(sample(rep(letters, 3)), nrow = 6)
    m
         [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13]
    [1,] "o"  "j"  "y"  "a"  "s"  "a"  "j"  "g"  "p"  "x"   "x"   "p"   "y"  
    [2,] "c"  "h"  "l"  "e"  "l"  "z"  "m"  "f"  "x"  "n"   "d"   "v"   "o"  
    [3,] "r"  "g"  "z"  "m"  "h"  "p"  "q"  "v"  "v"  "a"   "e"   "c"   "o"  
    [4,] "m"  "l"  "b"  "w"  "k"  "n"  "f"  "s"  "b"  "u"   "d"   "h"   "y"  
    [5,] "r"  "u"  "i"  "u"  "w"  "e"  "t"  "f"  "r"  "w"   "t"   "t"   "z"  
    [6,] "q"  "q"  "n"  "i"  "g"  "s"  "k"  "k"  "c"  "j"   "i"   "d"   "b"  
    
    table(m)
    m
    a b c d e f g h i j k l m n o p q r s t u v w x y z 
    3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3