How to Check If File or Folder Exists in R

To check if a file exists is a very useful operation before reading it in to avoid an error. To know your active directory in R, use the getwd() command.

getwd()

The getwd() function returns an absolute filepath representing the current working directory of the R process.

Checking If a file or folder exists in R

To check if the file or folder exists in R, use the file.exists() method. The file.exists() method returns the logical vector indicating whether the files named by its argument exist.

Syntax of file.exists()

file.exists(paths)

Arguments

paths: They are character vectors containing file names or paths.

Example

Let’s check if the file is there in the current working directory using the file.exists() method.

file <- "Pro.R"

if (file.exists(file)) {
 cat("The file is there")
} else {
 cat("The folder does not exist")
}

Right now, the Pro.R file is there in my current working directory. So, the if condition returns TRUE.

The file is there

If the file does not exist, then if condition returns FALSE and else block will execute.

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

How to check if a directory exists

To check if the directory exists in R, use the file.exists() method.

folder <- "Ampol"

if (file.exists(folder)) {
 cat("The folder exists")
} else {
 cat("The folder does not exist")
}

Output

The folder does not exist

And that means our current directory does not have Ampol as a directory.

That is it for this tutorial.

Leave a Comment