R:如果循环中使用的函数具有 stop() clausule,则继续循环到下一次迭代



我创建了一个函数,该函数读取数据集,但是当驱动器上不存在此特定文件时返回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 循环中的迭代。

当函数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") ) {

最新更新