使用R中的rbinom随机生成1和2的二项式值

qxsslcnc  于 2023-06-19  发布在  其他
关注(0)|答案(1)|浏览(116)

我试图使用rbinom()生成一个二项分布的随机数。但是,我不想生成0或1,而是想用值2替换0。我尝试过rbinom(n=1, size = 1, prob = 0.75) + 1,然后在 Dataframe 中将值2更改为值1,反之亦然,但我正在努力制定一个不需要这样做的解决方案。我曾想过以类似的方式使用sample.int(),但也为此而挣扎。
我想知道是否可以将rbinom的二项分布中的0替换为值2,以便它从2或1而不是0或1中提取。

xurqigkl

xurqigkl1#

要从概率为c(0.25, 0.75)的向量x = c(1,2)中采样,可以使用

sample.int(2, 1, prob=c(0.25, 0.75))

s = rbinom(1, 1, prob = 0.25) # sample zeros or ones
# and convert zeros to two
2 - s

通过绘制更多样本检查它是否给出预期结果

set.seed(76422247)
s = sample.int(2, 1e6, TRUE, prob=c(0.25, 0.75))
proportions(table(s))
#        1        2 
# 0.250207 0.749793 

set.seed(76422247)
s2 = 2 - rbinom(1e6, 1, prob = 0.25)
proportions(table(s2))
#        1        2 
# 0.250207 0.749793

相关问题