r – Check existence of directory and create if doesnt exist

r – Check existence of directory and create if doesnt exist

Use showWarnings = FALSE:

dir.create(file.path(mainDir, subDir), showWarnings = FALSE)
setwd(file.path(mainDir, subDir))

dir.create() does not crash if the directory already exists, it just prints out a warning. So if you can live with seeing warnings, there is no problem with just doing this:

dir.create(file.path(mainDir, subDir))
setwd(file.path(mainDir, subDir))

As of April 16, 2015, with the release of R 3.2.0 theres a new function called dir.exists(). To use this function and create the directory if it doesnt exist, you can use:

ifelse(!dir.exists(file.path(mainDir, subDir)), dir.create(file.path(mainDir, subDir)), FALSE)

This will return FALSE if the directory already exists or is uncreatable, and TRUE if it didnt exist but was succesfully created.

Note that to simply check if the directory exists you can use

dir.exists(file.path(mainDir, subDir))

r – Check existence of directory and create if doesnt exist

Heres the simple check, and creates the dir if doesnt exists:

## Provide the dir name(i.e sub dir) that you want to create under main dir:
output_dir <- file.path(main_dir, sub_dir)

if (!dir.exists(output_dir)){
dir.create(output_dir)
} else {
    print(Dir already exists!)
}

Leave a Reply

Your email address will not be published.