尝试在 R 中的 for 循环中捕获

时间:2021-02-21 10:38:58

标签: r

我有一个关于在 R 中实现 tryCatch 的问题。我有一个运行多元宇宙分析的 for 循环(阅读同一测试的许多变体)。但是,在运行测试之前,我对自变量进行了混洗。有时,这会导致自变量的不幸组合,从而无法运行分析,并且分析会引发错误。现在,我希望循环重新洗牌并在发生这种情况时重试。从之前的堆栈溢出帖子中,我看到 tryCatch 应该按照我的意愿行事,但是我找不到有关如何正确实现 tryCatch 的任何信息。有没有人有链接或知道怎么做?

请在下面找到我的代码:

#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))
  
}

2 个答案:

答案 0 :(得分:2)

您只需使用 OneToOneField 即可。我会使用 while 循环,以便它只重试直到 500 次完成运行。像这样

ManyToManyField

答案 1 :(得分:0)

Skipping error in for-loop 提供了很好的响应!

抱歉,我之前没有看到!