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

Kelly Nguyen picture Kelly Nguyen · Apr 4, 2014 · Viewed 40.7k times · Source

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.

Answer

user42628 picture user42628 · Apr 4, 2014

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