Check Existence of Local File in R (2 Examples)

 

This tutorial explains how to test whether a file exists in a local directory in the R programming language.

The post is structured as follows:

Here’s the step-by-step process:

 

Example 1: Checking If File Exists

In this Example, I’ll illustrate how to use the file.exists() function in R to test if a data file is existing in a local folder on your computer. The file.exists command can be applied as follows:

file.exists("data.csv")         # Apply file.exists function
# FALSE

As you can see, the file.exists function returned the logical value FALSE to the RStudio console. In other words: The csv file data.csv is not stored in the current working directory.

Note that we have not explicitly specified a working directory and by default the file.exists function searches in the currently used working directory of RStudio. In case you want to check a specific folder, you may use the setwd function first; or you may specify the path to the working directory within the file.exists function.

However, let’s create some data…

data <- data.frame(x = 1:5,     # Create some data
                   y = 1:5)

…that we can export to our currently used working directory as csv:

write.csv2(data, "data.csv")    # Write data to csv file

Now, let’s apply the file.exists function again:

file.exists("data.csv")         # Apply file.exists again
# TRUE

This time the function is telling us that the csv-file data.csv is contained in our working directory.

 

Example 2: Checking If File Does NOT Exist

In this Example, I’ll show how to use the file.exists function the opposite way, i.e. how to test whether a file does NOT exist. For this, we simply have to add a bang sign (i.e. !) in front of the function:

!file.exists("data.csv")        # file.exists function with !
# FALSE

In this case, the RStudio console is showing the logical value FALSE.

 

Video & Further Resources

I have recently released a video instruction on my YouTube channel, which shows the content of this article. You can find the video below:

 

The YouTube video will be added soon.

 

In addition, you might have a look at the other articles of this website. I have released several other articles already.

 

You learned in this tutorial how to check folders on your computer for specific file names in the R programming language. Let me know in the comments section, in case you have further questions. Besides that, don’t forget to subscribe to my email newsletter to get regular updates on new tutorials.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top