站成一排的学生
Students standing in a line
所以我正在研究统计问题,问题是 "Six kids are standing in line. What is the probability that they are in alphabetical order by name? Assume no two children have the same exact name." 我在 R 中使用 sample() 和 rle() 函数,但我对如何计算概率感到困惑.我可以得到一些帮助吗?
这也是我目前的代码:
kids <- sample(c("A", "B", "C", "D", "E", "F"), 6, replace = TRUE)
table(kids)
head(kids)
rle(c("A", "B", "C", "D", "E", "F"))
kids.rle <- rle(kids)
str(kids.rle)
sort(kids.rle$lengths, decreasing = TRUE)
如@YOLO 所述,理论概率为 1 / 720
,可以在 R 中计算为 1 / factorial(6)
。但是,您也可以轻松地在脑海中计算出来。如果您想 运行 一个小的模拟来表明随着重复次数的增加,观察到的概率收敛到理论概率,计算能力会派上用场:
kids_ordered <- c("A", "B", "C", "D", "E", "F")
n <- 1000000 # number of repetition
result <- rep(NA, n) # vector to hold outcomes
set.seed(147) # seed for reproducibility
# reorder kids n times and check if the outcome is in alphabetical order each time
for(i in seq_len(n)) {
result[i] <- all(sample(kids) == kids_ordered)
}
# compute the probability
mean(result)
# [1] 0.001376
结果非常接近1 / 720 = 0.001389
所以我正在研究统计问题,问题是 "Six kids are standing in line. What is the probability that they are in alphabetical order by name? Assume no two children have the same exact name." 我在 R 中使用 sample() 和 rle() 函数,但我对如何计算概率感到困惑.我可以得到一些帮助吗?
这也是我目前的代码:
kids <- sample(c("A", "B", "C", "D", "E", "F"), 6, replace = TRUE)
table(kids)
head(kids)
rle(c("A", "B", "C", "D", "E", "F"))
kids.rle <- rle(kids)
str(kids.rle)
sort(kids.rle$lengths, decreasing = TRUE)
如@YOLO 所述,理论概率为 1 / 720
,可以在 R 中计算为 1 / factorial(6)
。但是,您也可以轻松地在脑海中计算出来。如果您想 运行 一个小的模拟来表明随着重复次数的增加,观察到的概率收敛到理论概率,计算能力会派上用场:
kids_ordered <- c("A", "B", "C", "D", "E", "F")
n <- 1000000 # number of repetition
result <- rep(NA, n) # vector to hold outcomes
set.seed(147) # seed for reproducibility
# reorder kids n times and check if the outcome is in alphabetical order each time
for(i in seq_len(n)) {
result[i] <- all(sample(kids) == kids_ordered)
}
# compute the probability
mean(result)
# [1] 0.001376
结果非常接近1 / 720 = 0.001389