随机数发生器/硬币翻转/ A-B发生器 - 在R中连续运行X.

时间:2015-07-26 18:06:23

标签: r coin-flipping

我正在尝试生成随机结果,例如来自硬币翻转。我想运行这个A / B或头/尾发生器,直到我连续得到相同结果的x。

我在网上找到了这个代码,用于翻转硬币:

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))

这可以产生20次翻转,但我想要做的是让“翻转模拟器”运行,直到我连续得到x相同的结果。

3 个答案:

答案 0 :(得分:4)

您可以使用简单的循环

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
}

答案 1 :(得分:2)

一种方法可能是生成大量的硬币翻转,并在第一次使用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 :(得分:0)

比@nongkrong的答案长一点,但实际上你得到了一些输出:

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

示例:

> out
  CoinFlip
1        1
2        0
3        1
4        0
5        0
6        0
7        0
8        0