首页 > 解决方案 > 将值添加到向量,直到其总和在某个范围内

问题描述

我正在尝试在 R 中编写一个简单的脚本来输出二项式分布值的向量,使得这些值的总和在给定范围内。我知道我需要使用命令 rbinom 从二项式分布中绘制值,但我不知道如何编写代码以便一次绘制一个值,直到总和在给定范围内(并且不超过上限),然后代码停止。

我有使用 R 和 MATLAB 的基本经验,但就我的编程经验而言。

谢谢您的帮助!

标签: rbinomial-coefficients

解决方案


这里有很长的路可以帮助说明:

set.seed(101)
total  <- 0
trials <- 0
limit  <- 10
while(total < limit) {
  trials <- trials + 1
  total <- total + rbinom(1, 1, 0.5)
  cat("Number of trials: ", trials, "\t", "Total is: ", total, "\n")
}
#> Number of trials:  1      Total is:  0 
#> Number of trials:  2      Total is:  0 
#> Number of trials:  3      Total is:  1 
#> Number of trials:  4      Total is:  2 
#> Number of trials:  5      Total is:  2 
#> Number of trials:  6      Total is:  2 
#> Number of trials:  7      Total is:  3 
#> Number of trials:  8      Total is:  3 
#> Number of trials:  9      Total is:  4 
#> Number of trials:  10     Total is:  5 
#> Number of trials:  11     Total is:  6 
#> Number of trials:  12     Total is:  7 
#> Number of trials:  13     Total is:  8 
#> Number of trials:  14     Total is:  9 
#> Number of trials:  15     Total is:  9 
#> Number of trials:  16     Total is:  10

但是,呼叫rbinom将是资源密集型的。另一种方法是将n参数设置rbinom为大的,而不是使用类似的东西:

large_trials <- rbinom(60, 1, 0.5)
large_trials
#>  [1] 1 0 0 0 1 1 0 1 1 1 0 0 0 1 0 0 0 0 1 1 0 1 0 1 0 0 1 0 0 0 0 1 1 0 0
#> [36] 0 1 1 0 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 0 1 1 1 1 0

which.min(cumsum(large_trials) < limit)
#> [1] 22

推荐阅读