Random Number Generator / Flip / A -B Generator - Run up to X in a string in R

I am trying to generate random results, for example from coin flip. I would like to run this A / B or head / tails generator until I get x of the same result sequentially.

I found this code online to transfer coins:

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 I want the "flip simulator" to run until I get x of the same result per line.

+3


source to share


3 answers


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
}

      

+4


source


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

:



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

      

+2


source


Longer than @ nongkrong's answer, but you do 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

      

0


source







All Articles