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

假如想象 提交于 2019-12-21 07:26:46

问题


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.


回答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).




回答2:


1) If you use sample, this is sufficient:

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

e.g.:

 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:

 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; here's a sample of size 9:

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

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

3) you can use rbinom; here's a sample of size 4:

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

[1] -6  6 -6  6



回答3:


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
> 



回答4:


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)$. Since discrete distributions are much easier to generate with $\text{uniform}(0,1)$, people don't wrap up a function for them. However, you can write your own function and just pick them up next time you're going to use them.



来源:https://stackoverflow.com/questions/22893089/r-how-to-generate-random-sample-of-a-discrete-random-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!