[R] Need vector of random double exponentials

David Winsemius dwinsemius at comcast.net
Fri Mar 21 22:01:21 CET 2008


cammie12 at aol.com wrote in
news:8CA59A2EC4C0832-834-90 at MBLK-M13.sysops.aol.com: 

> Hi, I am fairly new to R, and am stuck. 

Please use an informative subject line when posting. (And read the 
Posting Guide. <http://www.R-project.org/posting-guide.html>
 
> I want to write an R function with argument n that returns a vector
> of length n with n simulated observations from the double
> exponential distribution with density: ??g(y) = 1/2e^-y 

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)

> 
> For the double exponential, I want to generate y~Exp(1) and then
> take ?y with probability 0.5 


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



More information about the R-help mailing list