【问题标题】:R: Continue loop to next iteration if function used in loop has stop() clausuleR:如果循环中使用的函数具有 stop() 子句,则继续循环到下一次迭代
【发布时间】:2020-06-04 12:52:41
【问题描述】:

我创建了一个函数,它读取数据集,但当驱动器上不存在此特定文件时返回 stop()。这个函数叫做sondeprofile(),但唯一重要的部分是:

if(file.exists(sonde)) {
    dfs <- read.table(sonde, header=T, sep=",", skip = idx, fill = T)
  } else {
    stop("No sonde data available for this day")
  }

然后在 for 循环中使用此函数来循环特定日期和站点以在每一天进行计算。极其简化的问题:

for(name in stations) {
    sonde <- sondeprofile(date)

    # Continue with loop if sonde exists, skip this if not
    if(exists("sonde")) {

        ## rest of code ## 
  }
}

但我的问题是,每当sondeprofile() 函数发现该特定日期没有文件时,stop("No sonde data available for this date") 就会导致上面的整个 for 循环停止。我认为通过检查文件是否存在就足以确保它跳过此迭代。但可惜我不能让它正常工作。

我希望每当sondeprofile() 函数发现没有特定日期的可用数据时,它会跳过迭代并且不执行其余代码,而只是转到下一个。

我怎样才能做到这一点? sondeprofile() 也用于代码的其他部分,作为独立函数,因此我需要它来跳过 for 循环中的迭代。

【问题讨论】:

  • sonde &lt;- sondeprofile(date) 替换为sonde &lt;- try(sondeprofile(date), silent = TRUE) 并将if(exists("sonde")) { 替换为if ( !inherits(sonde, "try-error") ) {
  • 这似乎可以解决问题!谢啦!现在运行整个代码,但它并没有同时停止。您想将此作为答案发布,以便我检查吗?
  • 当然。由于没有数据可以检查,我最初犹豫是否将其作为答案发布,但我现在将发布答案
  • 好的,我已经添加了,有一些解释

标签: r function loops for-loop


【解决方案1】:

当函数sondeprofile() 抛出错误时,它将停止整个循环。但是,您可以使用try() 来避免这种情况,它会尝试运行“可能失败并允许用户代码处理错误恢复的表达式”。 (来自help("try"))。

所以,如果你替换

sonde <- sondeprofile(date)

sonde <- try(sondeprofile(date), silent = TRUE)

您可以避免它停止循环的问题。但是你如何处理if() 条件呢?

好吧,如果try() 调用遇到错误,它返回的将是try-error 类。因此,您只需确保 sonde 不属于该类,正在更改

if(exists("sonde")) {

if ( !inherits(sonde, "try-error") ) {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-23
    • 1970-01-01
    • 1970-01-01
    • 2017-10-05
    • 2017-07-18
    • 2015-11-11
    相关资源
    最近更新 更多