简体   繁体   English

如何通过 R 中的样本 function 生成一系列数字,并在每次尝试中给出不同的概率?

[英]How to generate a series of number by function of sample in R, with given different probability in each try?

For example I have a vector about possibility is例如我有一个关于可能性的向量是

myprob <- (0.58, 0.51, 0.48, 0.46, 0.62)

And I want to sampling a series of number between 1 and 0 each time by the probability of c(1-myprob, myprob) ,我想每次以c(1-myprob, myprob)的概率对 1 到 0 之间的一系列数字进行采样,

which means in the first number in the series, the function sample 1 and 0 by (0.42, 0.58), the second by (0.49, 0.50) and so on,这意味着在系列中的第一个数字中,function 样本 1 和 0 为 (0.42, 0.58),第二个为 (0.49, 0.50) 等等,

how can I generate the 5 numbers by sample?如何通过样本生成 5 个数字?

The syntax of的语法

Y <- sample(c(1,0), 1, replace=F, prob=c(1-myprob, prob))

would have incorrect number of probabilities and only 1 number output if I specify the prob;如果我指定概率,概率的数量不正确,只有 1 个数字 output;

while the syntax of而语法

Y <- sample(c(1,0), 5, replace=F, prob=c(1-myprob, prob))

would have the probabilities focus on only 0.62(or not I am not sure, but the results seems not correct at all)概率只关注 0.62(我不确定,但结果似乎根本不正确)

Thanks for any reply in advance!感谢您提前回复!

If myprob is the probability of drawing 1 for each iteration, then you can use rbinom , with n = 5 and size = 1 (5 iterations of a 1-0 draw).如果myprob是每次迭代绘制 1 的概率,那么您可以使用rbinom ,其中n = 5size = 1 (1-0 绘制的 5 次迭代)。

set.seed(2)
rbinom(n = 5, size = 1, prob = myprob)
[1] 1 0 1 0 0

Maël already proposed a great solution sampling from a binomial distribution. Maël已经提出了一个很好的二项分布抽样解决方案。 There are probably many more alternatives and I just wanted to suggest two of them:可能还有更多选择,我只想推荐其中两个:

runif()运行程序()

as.integer(runif(5) > myprob)

This will first generate a series of 5 uniformly distributed random numbers between 0 and 1, then compare that vector against myprob and convert the logical values TRUE / FALSE to 1/0.这将首先生成一系列介于 0 和 1 之间的 5 个均匀分布的随机数,然后将该向量与myprob进行比较并将逻辑值TRUE / FALSE转换为 1/0。

vapply(sample()) vapply(样品())

vapply(myprob, function(p) sample(1:0, 1, prob = c(1-p, p)), integer(1))

This is what you may have been looking for in the first place.这可能是您最初一直在寻找的东西。 This executes the sample() command by iterating over the values of myprob as p and returns the 5 draws as a vector.这通过将myprob的值迭代为p来执行sample()命令,并将 5 次绘制作为向量返回。

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

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