Skip to content
Prev 140078 / 398506 Next

Need vector of random double exponentials

cammie12 at aol.com wrote in
news:8CA59A2EC4C0832-834-90 at MBLK-M13.sysops.aol.com:
Please use an informative subject line when posting. (And read the 
Posting Guide. <http://www.R-project.org/posting-guide.html>
I think that might be g(y) = (1/2)e^(-abs(y)). Johnson, Kotz and 
Balakrishnan "Cont. Univariate Distr. 2nd ed" illustrate the 
acceptance-rejection method for Laplace random numbers on p 154. At any 
rate, there is already a package that will generate the desired random 
numbers. 

help.search("double exponential")
#tells you:
#DExp-class(distr)             Class "DExp"
#so DExp is a class in the "distr" package
require(distr)
?DExp
?rexp

#make D a distribution argument to distr's r(), d(), and p() functions 
D <- DExp(rate=1)  #which is the Laplace fucntion
# make rvec a 100 element vector of random Dexp(rate=1)
rvec<-r(D)(100)
#create 100 random binomials
rprob<-rbinom(100,1,0.5)
head(rprob)
#[1] 0 0 1 0 1 0
onehalf<-rvec*rprob

head(onehalf)
#0.0000000 0.0000000 0.6638434 0.0000000 0.4638312 0.0000000

Or if you didn't want the extraneous zeros as placeholders you could 
strip them out with:

onehalf[onehalf != 0]
#[1]  0.663843413  0.463831152  2.586626569  1.227912636  3.860839987 
# -3.394600764  0.542588566  <snip>

Note: this does not give you 50 elements every time.