简体   繁体   English

R:矢量化样本,每次采样的概率都不同

[英]R: vectorized sample where the probability varies each time you sample

I'm trying to sample 10 values of either 0 or 1, with defined (but different) probabilities each time. 我正在尝试对10个0或1的值进行采样,每次都定义(但不同)概率。

This does not work: 这不起作用:

sample(0:1, size = 10, replace = T, prob = seq(0.1, 1, 0.1))

This does work: 这确实有效:

sapply(seq(0.1, 1, 0.1), function(x) sample(0:1, size = 1, prob = c(1-x, x)))

The 10th value is always 1, while the first value has a 1/10 chance of being a 1 - which is what I want to achieve. 第十个值始终为1,而第一个值具有1的1/10概率为1-这是我想要实现的。

Is there a vectorized approach? 有矢量化方法吗?

您想从二项分布中进行采样:

rbinom(10, 1, prob = seq(0.1, 1, 0.1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM