随机数生成器/抛硬币/A-B生成器-运行到R中的一行X

随机数生成器/抛硬币/A-B生成器-运行到R中的一行X,r,coin-flipping,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

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

sample.space您可以使用一个简单的循环

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
}

n一种方法可以是生成大量的抛硬币,并使用
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

first.conce比@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