r - 将值添加到向量,直到其总和在某个范围内
问题描述
我正在尝试在 R 中编写一个简单的脚本来输出二项式分布值的向量,使得这些值的总和在给定范围内。我知道我需要使用命令 rbinom 从二项式分布中绘制值,但我不知道如何编写代码以便一次绘制一个值,直到总和在给定范围内(并且不超过上限),然后代码停止。
我有使用 R 和 MATLAB 的基本经验,但就我的编程经验而言。
谢谢您的帮助!
解决方案
这里有很长的路可以帮助说明:
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
推荐阅读
- ruby-on-rails - has_one 虽然 has_one 的构建方法
- r - 在 R 中使用 fakeR 模拟数据
- mysql - 我怎么能使用 IN close 两次?
- amp-html - 显示从 json 到 AMP 页面的原始 HTML
- javascript - 如何在 Js 中以函数式方式编写代码
- c# - NativeScript HTTP 请求承诺 + WebApi 错误
- magento2 - Magento 2 - 图片标签返回产品名称
- azure-devops - 使用自定义函数应用编辑模式从 ARM 创建 Azure 函数
- ruby-on-rails - CircleCI 2.0 - 退出代码 127,找不到捆绑命令
- bash - 使用 BASH 安装软件