Home » How to Check if a Directory Exists in R (With Example)

How to Check if a Directory Exists in R (With Example)

by Erma Khan

You can use the following methods to check if a directory exists in R:

Method 1: Check If Directory Exists

dir.exists(file.path(main_dir, sub_dir))

This function will return TRUE if the directory exists and FALSE if it does not.

Method 2: Create Directory If It Doesn’t Exist

#define directory
my_directory path(main_dir, sub_dir)

#create directory if it doesn't exist
if (!dir.exists(my_directory)) {dir.create(my_directory)}  

Note that main_dir and sub_dir are strings that specify main directory and sub directory paths.

The following examples show how to use each method in practice.

Example 1: Check If Directory Exists

Suppose we would like to check if the following directories exist:

  • “C:/Users/bob/”
  • “C:/Users/bob/Documents”
  • “C:/Users/bob/Data_Science_Documents”

We can use the following syntax to do so:

#define main directory
main_dir #define various sub directories
sub_dir1 #check if main directory exists
dir.exists(file.path(main_dir))

[1] TRUE

#check if main directory and sub directory 1 exists
dir.exists(file.path(main_dir, sub_dir1))

[1] TRUE

#check if main directory and sub directory2 exists
dir.exists(file.path(main_dir, sub_dir2))

[1] FALSE

From the output we can see:

  • “C:/Users/bob/” – Exists
  • “C:/Users/bob/Documents” – Exists
  • “C:/Users/bob/Data_Science_Documents” – Does Not Exist

Method 2: Create Directory If It Doesn’t Exist

Suppose we would like to create the following directory if it doesn’t already exist:

  • “C:/Users/bob/Data_Science_Documents”

We can use the following syntax to do so:

#define main directory
main_dir 

#define sub directory
sub_dir 

#define directory
my_directory path(main_dir, sub_dir)

#create directory if it doesn't exist
if (!dir.exists(my_directory)) {dir.create(my_directory)}  

If we navigate to this folder on our computer, we can see that this directory did not exist but has now been created:

Note that if this directory already existed, a new one would not be created.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Load Multiple Packages in R
How to Check if a Package is Installed in R
How to Clear the Environment in R

Related Posts