You can use the following basic syntax to check if a file exists in your current working directory in R:
file.exists('my_data.csv')
This function will return TRUE if the file exists or FALSE if it does not.
You can also use an if else statement to read a file into R only if it exists:
data my_data.csv' if(file.exists(data)){ df csv(data) } else { print('Does not exist') }
The following example shows how to use these functions in practice.
Example: Check if File Exists in R
Suppose my current working directory in R is a folder called test_data with three CSV files:
I can use list.files() to list out the names of every file in the working directory:
#display the names of every file in current working directory list.files() [1] "my_data.csv" "my_new_data.csv" "some_old_data.csv"
I can use file.exists() to check if a given file exists in the current working directory:
#check if file 'my_data.csv' exists in current working directory file.exists('my_data.csv') [1] TRUE
The function returns TRUE, which tells us that the file ‘my_data.csv’ does indeed exist in the current working directory.
We can then use the following if else statement to import a file only if it exists:
#define file name data my_data.csv' #import file only if it exists if(file.exists(data)){ df csv(data) } else { print('Does not exist') } #view contents of CSV file df team points assists 1 A 14 4 2 B 26 7 3 C 29 8 4 D 20 3
Since the file exists, we’re able to import it successfully.
However, suppose we attempt to import a file that does not exist:
#define file name data this_data.csv' #import file only if it exists if(file.exists(data)){ df csv(data) } else { print('Does not exist') } [1] "Does not exist"
We receive the message “Does not exist”, which tells us that a file called this_data.csv does not exist in the current working directory.
Additional Resources
The following tutorials explain how to use other common functions in R:
How to Read Zip Files in R
How to Import CSV Files into R
How to Import Excel Files into R
How to Rename Files in R