rnareplicate

R: repeate replicate if output is NA


I am solving numerically stochastic differential equation with use of diffeqr in R, check if the last value is large enough and replicate the process for 5 times. The piece of code for this part is:

for(i in 1:30){
  for(j in 1:15) {
    u0<-c(1.5e+6+i*5e+4,j*2e+5)
    data<-replicate(n=5,{
      prob <- de$SDEProblem(f,g,u0,tspan,p)
      fastprob<-diffeqr::jitoptimize_sde(de,prob)
      sol <- de$solve(fastprob,saveat=0.005)
      mat <- sapply(sol$u,identity)
      udf <- as.data.frame(t(mat))
      udf[40000,1]<1e+6}
    )
    sum(data)/length(data)
    res02_4[i,j]=sum(data)/length(data)
  }
}

However, sometimes of the the results is NA for whatever reason and so sum(data)/length(data) is also NA. In this case I want to redo entire replicate piece (until it is not NA). How I can organize this? First thing comes to mind is a combination of if() {} else {} but I think it'll be quite cumbersome construction - is there more elegant way?


Solution

  • You could pre-define data as NA, then wrap the replicate section in a while loop that runs one or more times until sum(data) is not NA

    for(i in 1:30){
      for(j in 1:15) {
        u0<-c(1.5e+6+i*5e+4,j*2e+5)
        data <- NA
        while(is.na(sum(data))) {
          data <- replicate(n = 5,{
            prob <- de$SDEProblem(f,g,u0,tspan,p)
            fastprob<-diffeqr::jitoptimize_sde(de,prob)
            sol <- de$solve(fastprob,saveat=0.005)
            mat <- sapply(sol$u,identity)
            udf <- as.data.frame(t(mat))
            udf[40000,1]<1e+6}
          )
        }
        sum(data)/length(data)
        res02_4[i,j]=sum(data)/length(data)
      }
    }
    

    Obviously, I can't demonstrate that this works because you haven't included the de object in your question.