分配由概率分布通知的特定数量的值(在 R 中) [英] Assigning a specific number of values informed by a probability distribution (in R)

查看:39
本文介绍了分配由概率分布通知的特定数量的值(在 R 中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,提前感谢您的帮助!

Hello and thanks in advance for the help!

我正在尝试生成一个向量,其中包含根据概率分布分配的特定数量的值.例如,我想要一个长度为 31 的向量,包含 26 个零和 5 个 1.(向量的总和应始终为 5.)但是,向量的位置很重要.为了确定哪些值应该是 1,哪些应该是 0,我有一个概率向量(长度为 31),如下所示:

I am trying to generate a vector with a specific number of values that are assigned according to a probability distribution. For example, I want a vector of length 31, contained 26 zeroes and 5 ones. (The total sum of the vector should always be five.) However, the location of the ones is important. And to identify which values should be one and which should be zero, I have a vector of probabilities (length 31), which looks like this:

probs<-c(0.01,0.02,0.01,0.02,0.01,0.01,0.01,0.04,0.01,0.01,0.12,0.01,0.02,0.01,
0.14,0.06,0.01,0.01,0.01,0.01,0.01,0.14,0.01,0.07,0.01,0.01,0.04,0.08,0.01,0.02,0.01)

我可以根据这个分布选择值并使用 rbinom 得到一个长度为 31 的向量,但我不能选择正好五个值.

I can select values according to this distribution and get a vector of length 31 using rbinom, but I can't select exactly five values.

Inv=rbinom(length(probs),1,probs)
Inv
[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0

有什么想法吗?

再次感谢!

推荐答案

仅使用加权 sample.int 来选择位置怎么样?

How about just using a weighted sample.int to select the locations?

Inv<-integer(31)
Inv[sample.int(31,5,prob=probs)]<-1
Inv
[1] 0 0 0 1 0 1 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0

这篇关于分配由概率分布通知的特定数量的值(在 R 中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆