Open In App

R – Check if a Directory Exists and Create if It does not

Improve
Improve
Like Article
Like
Save
Share
Report

Directories and sub-directories are accessed by their corresponding paths in the R Programming Language. It is easy to work with these in R and perform operations related to the creation, copy, and movement of folders and sub-folders within the system. In this article, we will see how to check if a directory exists and how to create a new directory if it does not exist using R Programming Language.

Directory in use:

Check if the existDirectory exists

The path corresponding to the main directory can be first stored in the working space. We can check if this directory exists, using the file.exists() method. This method returns a logical vector depicting whether the files specified by its argument exist in the space or not. If the file exists, it returns TRUE, otherwise FALSE is returned. 

Syntax: dir.exists(paths)

Parameter:

path – a character vector containing a single path name.

Example:

R




sub_dir<-"test1"
 
file.exists(sub_dir)


Output:

TRUE

Creating a directory if it does not exist

If the file exists the working directory is set to the path formed by the concatenation of the main and subdirectories respectively. Otherwise, the directory is created using the dir.create() method.  This method returns a logical vector describing if the creation of the file succeeded for each of the files for which it was attempted. dir.create indicates failure if the directory already exists.

Syntax: dir.create(path, showWarnings = TRUE, recursive = FALSE, mode = “0777”)

Parameter : 

  • path – a character vector containing a single path name.
  • showWarnings – logical; should the warnings on failure be shown?
  • mode – the mode to be used on Unix-alikes.

Example:

R




# setting up the main directory
main_dir <- "C:\\Users\\Vanshi\\Desktop\\gfg\\test"
 
# setting up the sub directory
sub_dir <- "abc"
 
# check if sub directory exists
if (file.exists(sub_dir)){
         
        # specifying the working directory
        setwd(file.path(main_dir, sub_dir))
} else {
         
        # create a new sub directory inside
        # the main path
        dir.create(file.path(main_dir, sub_dir))
         
        # specifying the working directory
        setwd(file.path(main_dir, sub_dir))
}


Output:



Last Updated : 20 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads