R Try reading a csv and if it doesn't exist read a different one

Viewed 204

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?

3 Answers

As suggested by @All Downhill From Here using file.exists would check if the file exists at the given location. As file.exists returns a logical value you can wrap it in if/else block.

if(file.exists('data.csv')) {
  data <- read.csv('data.csv')
} else {
  data <- read.csv('confirm.csv')
}

This also could be an option using purrr::map_if. First we create a character vector of our desired file names:

library(purrr)

vec <- c("data.csv")

vec %>% 
  map_if(~ file.exists(.x), ~ read.csv(.x, header = TRUE), 
         .else = read.csv(gsub("([a-z0-9_]+)\\.([a-z]+$)", "confirm\\.\\2", 
                                 vec, perl = TRUE), header = TRUE))

We may make use of an index

data <- read.csv(c("confirm.csv", "data.csv")[1 + file.exists("data.csv")])
Related