R-如何生成离散随机变量的随机样本? [英] R-How to generate random sample of a discrete random variables?
问题描述
在R中,我想生成一个离散随机变量的随机样本:X
,其中:P(X=a)=P(X=-a)=1/2
.我一直在在线寻找函数,但是似乎没有直接函数可以这样做.
In R, I want to generate a random sample of a discrete random variable: X
, where: P(X=a)=P(X=-a)=1/2
. I have been searching for a function online, but there seems no direct function doing this.
推荐答案
我认为您正在寻找生成伯努利随机变量的样本的方法.伯努利随机变量是二项式随机变量的特例.因此,您可以尝试rbinom(N,1,p)
.这将生成N
个样本,其值1
的概率为p
,值0
的概率为(1-p)
.要获取a
和-a
的值,可以使用a*(2*rbinom(N,1,p)-1)
.
I think you are looking to generate samples of a Bernoulli random variable. A Bernoulli random variable is a special case of a binomial random variable. Therefore, you can try rbinom(N,1,p)
. This will generate N
samples, with value 1
with probability p
, value 0
with probability (1-p)
. To get values of a
and -a
you can use a*(2*rbinom(N,1,p)-1)
.
这篇关于R-如何生成离散随机变量的随机样本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!