Reputation: 574
I have created a function that reads in a dataset but returns a stop() when this specific file does not exist on the drive. This function is called sondeprofile()
, but the only important part is this:
if(file.exists(sonde)) {
dfs <- read.table(sonde, header=T, sep=",", skip = idx, fill = T)
} else {
stop("No sonde data available for this day")
}
This function has then been used within a for-loop to loop over specific days and stations to do calculations on each day. Extremely simplified problem:
for(name in stations) {
sonde <- sondeprofile(date)
# Continue with loop if sonde exists, skip this if not
if(exists("sonde")) {
## rest of code ##
}
}
But my issue is whenever the sondeprofile()
functions finds that there is no file for this specific date, the stop("No sonde data available for this date")
causes the whole for loop above to stop. I thought by checking if the file exists it would be enough to make sure it skips this iteration. But alas I can't get this to work properly.
I want that whenever the sondeprofile()
function finds that there is no data available for a specific date, it skips the iteration and does not execute the rest of the code, rather just goes to the next one.
How can I make this happen? sondeprofile()
is used in other portions of the code as well, as a standalone function so I need it to skip the iteration in the for loop.
Upvotes: 0
Views: 1294
Reputation: 16910
When the function sondeprofile()
throws an error, it will stop your whole loop. However, you can avoid that with try()
, which attempts to try to run "an expression that might fail and allow the user's code to handle error-recovery." (From help("try")
).
So, if you replace
sonde <- sondeprofile(date)
with
sonde <- try(sondeprofile(date), silent = TRUE)
you can avoid the problem of it stopping your loop. But then how do you deal with the if()
condition?
Well, if a try()
call encounters an error, what it returns will be of class try-error
. So, you can just make sure that sonde
isn't of that class, changing
if(exists("sonde")) {
to
if ( !inherits(sonde, "try-error") ) {
Upvotes: 1