Search code examples
rfor-loopr2jags

How to pass control to previous iteration in for loop in R


I am running a for loop in R (as part of a power analysis for a model I ran with R2jags). At some point I want to know if my MCMC chains have converged, if not I want to skip that iteration of the loop. However, I don't want to skip to the next iteration, I want the loop start with the same iteration again. I am currently using the command 'next', but this is skipping the iteration. How do I tell my for loop to do an extra iteration? Below is the whole code, but it is basically this little bit that I am worried about:

  if(up1 > 1.1 | up2 > 1.1 | up3 > 1.1 | up4 > 1.1)
   next 

And this is the whole code:

G.vec <- rep(NA, 1000)
#-----model------

model1 <- function(){  

  # likelihood
  for (c in 1:16){
    D.diff[c] ~ dnorm(mu, tau)
  }

  # priors
  mu ~ dnorm(0, 10)
  tau <- 1/(sd*sd)
  sd ~ dunif(0, 10)
}

#---- for loop--------

for (i in 1:1000){


#--- data simulation ---------
# paired data
sim_bf <- rtnorm(16, mean = 0.4949, sd = 0.12, lower = 0.1)
sim_af <- rtnorm(16, mean = 0.3959, sd = 0.12, lower = 0.1)
diff = sim_bf - sim_af


#------setting up jags--------------

data <- list(D.diff = diff)
params <- c("mu", "tau", "sd")
inits <- function(){
  list(mu = rnorm(1),
       sd = rlnorm(1)) 
}

#-------run jags----------------

output <- jags(data=data, 
               # inits=inits, 
               parameters.to.save=params,
               n.iter=1000, 
               n.burn=100, 
               n.chains=2, 
               n.thin=1,
               model.file=model1,
               progress.bar = "gui")

#-------convergence checker----------------
output.mcmc <- as.mcmc(output)
x <- gelman.diag(output.mcmc)
up1 <- x$psrf[1,2]        # Approximate convergence is diagnosed when the upper limit is close to 1
up2 <- x$psrf[2,2] 
up3 <- x$psrf[3,2] 
up4 <- x$psrf[4,2] 


  if(up1 > 1.1 | up2 > 1.1 | up3 > 1.1 | up4 > 1.1)
   next                 

# one sided t-test
  lo = output$BUGSoutput$summary[2,4]
  G.vec[i] <- ifelse((lo < 0), 0, 1)
}

a <- table(G.vec)
G <- a[2]/1000
G

Solution

  • instead of

    for(i in 1:1000){...
        ...
        if(...
            next
    

    do

    i <- 0
    while(i <=1000){...
        i <- i+1
        ...
        if(...
            i <- i-1
            break