# [R] Is there a way to not use an explicit loop?

Victor Hernando Cervantes Botero vhcervantesb at unal.edu.co
Wed Sep 17 21:40:54 CEST 2008

```Hi,

you might try this:

set.seed(100)

m         <- 10
size.a    <- 10
prob.a    <- 0.3
prior.constant = 0

draw1 = rbinom( m , size.a, prob.a )

beta.draws <- function(draw, size.a, prior.constant, n) {
rbeta(n, prior.constant + draw, prior.constant + size.a - draw)
}

bdraws <- sapply(draw1, beta.draws, size.a = size.a, prior.constant =
prior.constant, n = 10000)
beta.post <- apply(bdraws, 2, function(x) c(post.mean = mean(x),
post.median = median(x)) )
beta.post
[,1]      [,2]      [,3]       [,4]      [,5]
[,6]      [,7]      [,8]
post.mean   0.2017118 0.1996809 0.2991173 0.10069613 0.3001924
0.2991149 0.4033310 0.2003104
post.median 0.1804893 0.1791630 0.2845427 0.07505278 0.2858155
0.2844503 0.3961419 0.1790511
[,9]     [,10]
post.mean   0.3013020 0.1990232
post.median 0.2886199 0.1786447

best

Víctor H Cervantes

2008/9/17 Juancarlos Laguardia <brassman785 at gmail.com>:
> I have a problem in where i generate m independent draws from a binomial
> distribution,
> say
>
> draw1 = rbinom( m , size.a, prob.a )
>
>
> then I need to use each draw to generate a beta distribution.  So, like
> using a beta prior, binomial likelihood, and obtain beta posterior, m many
> times.  I have not found out a way to vectorize draws from a beta
> distribution, so I have an explicit for loop within my code
>
>
>
> for( i in 1: m ) {
>
> beta.post = rbeta( 10000, draw1[i] + prior.constant  ,  prior.constant +
> size.a  - draw1[i] )
>
> beta.post.mean[i] = mean(beta.post)
> beta.post.median[i] = median(beta.post)
>
> etc.. for other info
>
> }
>
> Is there a way to vectorize draws from an beta distribution?
>
> UC Slug
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help