R – Check if a Directory Exists and Create if It does not
Directories and sub-directories are accessed by their corresponding paths in 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 Directory 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.
path – a character vector containing a single path name.
Creating a directory if it does not exists
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”)
- 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.