3

我正在尝试生成随机结果,例如掷硬币。我想运行这个 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 个相同的结果。

4

3 回答 3

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
}
于 2015-07-26T18:16:57.197 回答
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
于 2015-07-26T18:20:44.923 回答
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
于 2015-07-27T14:11:56.837 回答