Chase gives a great answer and mentions the run-away while() iteration problem. One of the problems with running while() is that if you do this one test at a time and it takes a lot, say t, of samples to find one that matches the target number 1 s, you bear the overhead t calls the main function, rbinom() in this case.
However, there is a solution, because rbinom() , like all these (pseudo) random number generators in R, is vectorized, we can generate m tests at a time and check these m tests to meet the requirements of 5 1 s. If none are found, we repeatedly collect m samples until we find one that matches. This idea is implemented in the foo() function below. The chunkSize argument is m, the number of samples to draw at a time. I also took the opportunity to let the function find more than one conformal test; argument n determines the number of conformal probes returned.
foo <- function(probs, target, n = 1, chunkSize = 100) { len <- length(probs) out <- matrix(ncol = len, nrow = 0)
It works as follows:
> set.seed(1) > foo(probs, target = 5) [1] 1 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 [31] 0 > foo(probs, target = 5, n = 2) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [1,] 0 0 0 0 0 0 0 0 0 0 0 [2,] 0 0 0 0 0 0 0 0 0 0 1 [,12] [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20] [,21] [1,] 0 0 0 1 1 0 0 0 0 0 [2,] 0 1 0 0 1 0 0 0 0 0 [,22] [,23] [,24] [,25] [,26] [,27] [,28] [,29] [,30] [,31] [1,] 1 0 1 0 0 0 1 0 0 0 [2,] 1 0 1 0 0 0 0 0 0 0
Please note that I delete the empty dimension in the case when n == 1 . Comment on the last if snippet if you don't want this feature.
You need to balance the size of chunkSize with the computational burden of checking that many trials at a time. If the requirement (here 5 1 s) is very unlikely, then increase chunkSize so that you have fewer calls to rbinom() . If this requirement is most likely, a small number of test drawings and large chunkSize at a time, if you want only one or two, how you should evaluate each test draw.