简体   繁体   English

R-如何生成离散随机变量的随机样本?

[英]R-How to generate random sample of a discrete random variables?

In R, I want to generate a random sample of a discrete random variable: X , where: P(X=a)=P(X=-a)=1/2 .在 R 中,我想生成一个离散随机变量的随机样本: X ,其中: P(X=a)=P(X=-a)=1/2 I have been searching for a function online, but there seems no direct function doing this.我一直在网上搜索一个函数,但似乎没有直接的函数这样做。

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) .因此,您可以尝试rbinom(N,1,p) This will generate N samples, with value 1 with probability p , value 0 with probability (1-p) .这将生成N样本,值为1的概率为p ,值为0的概率为(1-p) To get values of a and -a you can use a*(2*rbinom(N,1,p)-1) .要获取a-a值,您可以使用a*(2*rbinom(N,1,p)-1)

1) If you use sample , this is sufficient: 1)如果您使用sample ,这就足够了:

sample(c(-a,a),1)

eg:例如:

 a <- 10
 sample(c(-a,a),1)
[1] -10

Try another couple:尝试另一对:

> sample(c(-a,a),1)
[1] -10
> sample(c(-a,a),1)
[1] 10

Works.作品。

If you need to sample more than one element, then set replace=TRUE ... here we sample 12 times:如果您需要对多个元素进行采样,则设置replace=TRUE ... 这里我们采样 12 次:

 sample(c(-a,a),12,replace=TRUE)

 [1]  10  10 -10  10  10  10 -10 -10  10 -10  10 -10

2) you can use runif ; 2) 你可以使用runif ; here's a sample of size 9:这是一个大小为 9 的样本:

a <- 1
ifelse(runif(9)<.5,-a,a)

[1] -1  1 -1  1 -1  1 -1  1  1  

3) you can use rbinom ; 3)你可以使用rbinom here's a sample of size 4:这是一个大小为 4 的样本:

a <- 6
ifelse(rbinom(4,1,.5),-a,a)

[1] -6  6 -6  6

Or this:或这个:

> n=10
> X=rep(0,n)
> Y=rbinom(n,1,1/2)
> #Since they the probability is 1/2 for both cases, I assigned "a" when Y=1 and "-a" otherwise.
> X[Y==1]="a"
> X[Y==0]="-a"
> X
 [1] "a"  "-a" "a"  "a"  "a"  "-a" "a"  "-a" "-a" "-a"
> Y
 [1] 1 0 1 1 1 0 1 0 0 0
> 
index <- sample(1,c(1,2),replace=T)
if (index == 1) {xx = a} else {xx = -a}

Each distribution generating procedure begins with using $\\text{uniform}(0,1)$.每个分布生成过程都从使用 $\\text{uniform}(0,1)$ 开始。 Since discrete distributions are much easier to generate with $\\text{uniform}(0,1)$, people don't wrap up a function for them.由于使用 $\\text{uniform}(0,1)$ 更容易生成离散分布,因此人们不会为它们封装函数。 However, you can write your own function and just pick them up next time you're going to use them.但是,您可以编写自己的函数,并在下次使用它们时拿起它们。

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

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