# Re: [R] Rejection sampling to draw from distributions

From: Charles C. Berry <cberry_at_tajo.ucsd.edu>
Date: Fri, 14 Mar 2008 17:36:08 -0700

On Fri, 14 Mar 2008, Anup Nandialath wrote:

> Dear friends,
>
> Please find below the code that I have employed for a rejection sampler
> to draw from asymmetric laplace distributions. I was wondering if this
> code can be written more efficiently? Are there more efficient ways of
> drawing random numbers from asymmetric laplace distributions??
>

Usually.

It really helps to "provide commented, minimal, self-contained, reproducible code" as you are asked, but you have not shown what dal() is.

If dal() is **vectorized**, then a vectorized approach like this will often work well:

rout <- matrix(0,n)
rejected <- seq(n)
k <- n
while( k > 0 ){

rout[ rejected ] <- rnorm( k )
ratio <- dal(val=rout[ rejected ], p=p)/(s*dnorm(rout[ rejected ]))    alpha <- runif( k , min=0, max=1 )
rejected <- rejected[ alpha >= ratio ]    k <- length( rejected )
}

Obviously, I cannot test this without dal().

HTH, Chuck

p.s. Putting a limit on iterations is usually a good idea, too.

> Thanks in advance for your help and have a great weekend.
>
> Regards
>
> Anup
>
> ***********************************
> ral <- function(n,p,s=3)
> {
> rout <- matrix(0,n)
> for(i in 1:n)
> {
> repeat
> {
> root <- rnorm(1)
> ratio <- dal(val=root, p=p)/(s*dnorm(root))
> alpha <- runif(1, min=0, max=1)
> if(alpha<ratio)
> {break}
> }
> rout[i,] <- root
> }
> return(rout)}
>
>
>
> ---------------------------------
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help_at_r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> and provide commented, minimal, self-contained, reproducible code.
>

```Charles C. Berry                            (858) 534-2098
Dept of Family/Preventive Medicine
E mailto:cberry_at_tajo.ucsd.edu	            UC San Diego
```
http://famprevmed.ucsd.edu/faculty/cberry/ La Jolla, San Diego 92093-0901

R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Sat 15 Mar 2008 - 00:39:25 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sat 15 Mar 2008 - 04:30:22 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.