3

I am trying to generate random results, such as from a coin flip. I'd like to run this A/B or heads/tails generator until I get x of the same result consecutively.

I found this code online for a coin flip:

sample.space <- c(0,1)
theta <- 0.5 # this is a fair coin
N <- 20 # we want to flip a coin 20 times
flips <- sample(sample.space, 
size=N,
replace=TRUE,
prob=c(theta,1-theta))

This works to generate 20 flips, but what I want to do is have the 'flip simulator' run until I get x of the same result in a row.

josliber
  • 41,865
  • 12
  • 88
  • 126

3 Answers3

4

You can use a simple loop

n <- 10                                           # get this many 1s in a row
count <- runs <- 0                                # keep track of current run, and how many total
while(runs < n) {                                 # while current run is less than desired
    count <- count+1                              # increment count
    runs <- ifelse(sample(0:1, 1), runs+1, 0)     # do a flip, if 0 then reset runs, else increment runs
}
Rorschach
  • 28,468
  • 5
  • 66
  • 112
2

One approach could be to generate a large number of coin flips and identify the first time you get the specified number of consecutive flips using the rle function:

first.consec <- function(num.consec, num.flip) {
  flips <- sample(0:1, size=num.flip, replace=TRUE, prob=c(0.5, 0.5))
  r <- rle(flips)
  pos <- head(which(r$lengths >= num.consec), 1)
  if (length(pos) == 0) NA  # Did not get any runs of specified length
  else sum(head(r$lengths, pos-1))
}
set.seed(144)
first.consec(10, 1e5)
# [1] 1209
first.consec(10, 1e5)
# [1] 2293
first.consec(10, 1e5)
# [1] 466
josliber
  • 41,865
  • 12
  • 88
  • 126
0

A bit longer than @nongkrong's answer, but you actually get some output:

n <- 5
out <- 2
tmp2 <- 2
count <- 0
while (count < n-1) {
    tmp <- sample(0:1,1)
    out <- rbind(out, tmp)
    ifelse(tmp == tmp2, count <- count+1, count <- 0)
    tmp2 <- tmp
}
out <- data.frame(CoinFlip=out[-1])
out

Example:

> out
  CoinFlip
1        1
2        0
3        1
4        0
5        0
6        0
7        0
8        0
iraserd
  • 599
  • 1
  • 6
  • 22