[R] Elegant Code

Berend Hasselman bhh at xs4all.nl
Fri Mar 16 08:35:27 CET 2012


On 16-03-2012, at 08:09, Raphael Fraser wrote:

> Hi,
> 
> Can anyone help to write a more elegant version of my code? I am sure
> this can be put into a loop but I am having trouble creating the
> objects b1,b2,b3,...,etc.
> 
> b1 <- rigamma(50,1,1)
> theta1 <- rgamma(50,0.5,(1/b1))
> sim1 <- rpois(50,theta1)
> 
> b2 <- rigamma(50,1,1)
> theta2 <- rgamma(50,0.5,(1/b2))
> sim2 <- rpois(50,theta2)
> 
> b3 <- rigamma(50,1,1)
> theta3 <- rgamma(50,0.5,(1/b3))
> sim3 <- rpois(50,theta3)
> 
> b4 <- rigamma(50,1,1)
> theta4 <- rgamma(50,0.5,(1/b4))
> sim4 <- rpois(50,theta4)
> 
> b5 <- rigamma(50,1,1)
> theta5 <- rgamma(50,0.5,(1/b5))
> sim5 <- rpois(50,theta5)
> 
> 
> 
> par(mfrow=c(1,5))
> boxplot(sim1)
> boxplot(sim2)
> boxplot(sim3)
> boxplot(sim4)
> boxplot(sim5);


Not reproducible since rigamma is not a standard function.
What package?

Why store results in separate variables?
Use matrices then it become much easier.

Like this

N <- 5
Nsample <- 50

# temporary
rigamma <- function(n,a,b) runif(n)

b     <- matrix(0,N*Nsample,nrow=N)
theta <- matrix(0,N*Nsample,nrow=N)
sim   <- matrix(0,N*Nsample,nrow=N)

for( k in 1:N ) {
    b[k, ]    <- rigamma(Nsample, 1, 1)
    theta[k,] <- rgamma(Nsample,0.5,(1/b[k,]))
    sim[k,]   <- rpois(Nsample,theta[k,])
}

par(mfrow=c(1,N))
for( k in 1:N) boxplot(sim[k,])

Berend



More information about the R-help mailing list