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