I have a script where I'd prefer to read in a certain file, but if that file doesn't exist then I want to read in a different file. Files change by day so I don't want to pick and choose manually.
I'm currently using tryCatch to do this. Basically, try to read the first file, and if there's an error then return an empty df. Then have logic where if the table is blank, read in the file I know exists. While my solution works, it feels extremely clunky and I'd like to learn best practices going forward.
Current solution:
df <- suppressWarnings(tryCatch({read.csv('this file will not exist on your computer', stringsAsFactors = FALSE)},
error = function(e) data.frame()
))
if(nrow(df) == 0){
df <- cars # this will be a file I know exists
}
## Continue with function using a df I know exists ##
I don't love using suppressWarnings if I don't need to, but I disliked the warning that kept popping up (obviously the file doesn't exist that's why I'm tryCatching).
Ideally this could be a 3-line code. 1) Check if file exists. 2) If it does exist then read it. 3) If it doesn't exist, then read the other file I know exists. Any thoughts?