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