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.

有帮助吗?

解决方案

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

其他提示

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

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)$. 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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top