2

I have a question about implementing tryCatch in R. I have a for loop which runs a multiverse analysis (read many variations of the same test). However, before running the test, I shuffle the independent variables. Sometimes, that results in an unlucky combination of independent variables, which makes it impossible to run the analysis, and the analysis throws an error. Now, I would like the loop to just reshuffle and try again whenever that happens. From previous stack overflow posts I saw that tryCatch should do what I want it to, but I can´t find any information on how to implement tryCatch properly. Does anyone have a link or knows how to do that?

Please find below my code:

#Note: This won´t run on your machine, because it uses self-written functions which are too long to post here. It would be sufficient if you can tell me where to put the tryCatch things or send me to a link which explains how to use it to avoid loop terminations.
#setup up numer of iterations for permutations
permutation <-  1:500
#setup count of iterations
count <- 0
set.seed(117)
#set up empty dataframe
df_permutation <- data.frame()

#set up permutation loop
for (i in permutation){
  
  #shuffling of the independent variables
  simulate$shuffledemotion <- permute(simulate$Emotion)
  simulate$shuffledgender <- permute(simulate$ModelGender)
  simulate$shuffledmask <- permute(simulate$MaskStatus)
  
  #run the multiverse, make sure it has the same settings as the original multiverse
  df_mult_sim_shuffled <- multiverse.freq.anova(dataframe = simulate, valuevariable = "latency", idvariable = "pp_num", within1 = "shuffledemotion", within2 = "shuffledmask", within3 = "shuffledgender", between1 = NA, TransformationTypes = c("raw"),  FixedTrimmingTypes = c("nofixedtrimming"), DataTrimmingTypes = c("notrimming"), data.lower = 1, data.upper = 3, data.step =0.5, fixed.min.lower = 0.05, fixed.min.upper = 0.3, fixed.min.step = 0.05, fixed.max.lower = 8, fixed.max.upper = 10, fixed.max.step = 0.1, RawData = TRUE)
  
  #add +1 to the count for each iteration
  count = count + 1

  #save the dataset
  df_permutation_prelim <- as.data.frame(cbind(df_mult_sim_shuffled, count))
  df_permutation <- as.data.frame(rbind(df_permutation, df_permutation_prelim))
  
}
Max
  • 121
  • 1
  • 10

2 Answers2

2

You can do it just with try. I'd use a while loop so that it just retries until 500 completed runs. Something like this

count <- 0
set.seed(117)
while (count < 500) {
  x <- try({
    # replace this with your code
    if (runif(1) > 0.99) stop()
  })
  if (!inherits(x, 'try-error')) count <- count+1 else message('tried but failed ', count)
}
pseudospin
  • 2,737
  • 1
  • 4
  • 19
0

Skipping error in for-loop provides a good response!

Sorry, I haven´t seen that earlier!

Max
  • 121
  • 1
  • 10