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

标签 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 个相同的结果。

最佳答案

你可以使用一个简单的循环

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
}

关于随机数生成器/硬币翻转/A-B 生成器 - 在 R 中连续运行直到 X,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31640256/

相关文章:

r - 为什么抑制Rmarkdown中的错误不起作用?

r - 使用 bookdown 时在 rmarkdown 文档中包含 git 代码

抛硬币程序问题,C 编程

c++ - 在C++中模拟抛硬币时,模如何工作?

c - 宣布抛硬币游戏的获胜者

按组删除重复的年份行

r - 增加ggplot中的条之间的空间

r - 面积图 : cannot get stacking in correct order - legend out of sync with Data