How to create a directory if it does not exist in R

In this tutorial we will learn how to create a directory if it does not exist already using R. We will be using two base R functions, one of checking if a directory exists and the other for creating a directory. If a directory exists already we would not be creating it and if the directory does not exist, we will create a new directory using the R functions.

Find out if a directory exists or not using dir.exists()

Let us get started with checking if a directory exists or not.

In R, we can use dir.exists() function to check if a directory exists or not. dir.exists() will return TRUE if the directory exists and FALSE otherwise.

Let us check for a director named “output” exists or not at the current working directory. Also assume that the directory “output” does not exist. Therefore when we use dir.exists(), we would get FALSE

dir.exists("output")

## [1] FALSE

Create a directory using dir.create() in R

Since the directory does not exist let us try to create the director using dir.create() function.

dir.create("output")

Now if we check if the directory exists using dir.exists(), we will get TRUE as answer.

dir.exists("output")

## [1] TRUE

Note that if you try to create a directory that already exists, we would get the following warning

dir.create("output")

Warning in dir.create("output") : 'output' already exists

We can wrap these two functions using if statement to create a directory if it does not exist. As we explained, we will create the directory if does not exist already, otherwise just print the statement that it already exists.

if (!dir.exists("output")){
  dir.create("output")
}else{
  print("dir exists")
}
Exit mobile version