R Advanced

How to Create Directory and File If It doesn’t Exist in R

When working with file systems, checking the directory or file existence is always better before commencing the operations.

For a directory

To create a directory, if it does not exist, use the dir.exists() function. After checking its existence, if it does not exist, you can use the dir.create() function to create a new directory with a specified path.

    Here is the current snapshot of a directory:

    You can see that our directory is empty.

    Now, we will check programmatically if a directory exists. If not, it will create a folder.

    folder <- "./dir/newfolder"
    
    if (dir.exists(folder)) {
     cat("The folder already exists")
    } else {
     dir.create(folder)
    }
    

    Now, we will check if a new directory, “newfolder”, has been created.

    You can see from the screenshot that we successfully created a folder because it did not exist.

    Nested directories

    If you also want to create a parent directory, pass recursive = TRUE to the dir.create() function. For example, we can create a directory structure like this: parent/child/grandchild

    nested_dir <- "parent/child/grandchild"
    
    if (!dir.exists(nested_dir)) {
      # Use recursive = TRUE for nested folders if needed
      dir.create(nested_dir, recursive = TRUE)
      cat("Directory created:", nested_dir, "\n")
    } else {
      cat("Directory already exists:", nested_dir, "\n")
    }

    For a directory

    To create a file if it does not exist, use the file.exists() function along with the file.create() method.

    The file.create() function creates files with the given names if they do not already exist and truncates them if they do.

    Let’s check the current status of our directory, and if it does not exist, we will create a file.

    You can see that we only have one folder in our directory.

    file <- "./dir/main.R"
    
    if (file.exists(file)) {
      cat("The file already exists")
    } else {
      file.create(file)
      cat("File is created!")
    }
    

    Our code ran successfully and printed “File is created”. Let’s go to the directory and check if it has been created.

    And now we can confirm that it did create a file.

    If you rerun the code, it will not create a file because it already exists.

    By default, file.create() function will overwrite the file if it exists. So, if the checks are not in place, it could be hazardous.

    Error handling

    Since file handling operations are error-prone, we can use the tryCatch() function to handle as many errors as possible. For example, we might face permission-related issue while creating a directory or file.

    nested_dir <- "parent/child/grandchild"
    
    if (!dir.exists(nested_dir)) {
      tryCatch(
      {
        dir.create(nested_dir, recursive = TRUE)
        cat("Directory created:", nested_dir, "\n")
      },
      error = function(e) {
        message("Error creating directory: ", e$message)
      }
     )
    } else {
      cat("Directory already exists:", nested_dir, "\n")
    }

    In this code, we can handle the possible errors while generating a new directory and print the error message if any.

    Using the fs Package

    R provides a built-in fs package that can be used to create a file or directory based on our requirements. It provides dir_create() and file_create() functions for consistent file operations.

    Remove the parent directory we created in the above programs, so that here, we can create in this code example:

    library(fs)
    
    nested_dir <- "parent/child/grandchild"
    file <- "parent/child/grandchild/data.R"
    
    if (!dir.exists(nested_dir)) {
      tryCatch(
      {
        dir_create(nested_dir)
        cat("Directory created:", nested_dir, "\n")
        
        file_create(file)
        cat("File created:", file, "\n")
      },
      error = function(e) {
      message("Error creating directory: ", e$message)
      }
     )
    } else {
      cat("Directory already exists:", nested_dir, "\n")
      cat("File already exists:", file, "\n")
    }
    

    Temporary files

    If you want to create temporary files, you can use the built-in tempfile() function.

    temp_file <- tempfile(pattern = "temp_", fileext = ".txt")
    
    file.create(temp_file)
    
    # [1] TRUE

    That’s it!

    Recent Posts

    How to Check If File and Folder Already Exists in R

    Whether you are reading or writing files via programs in the file system, it is…

    1 day ago

    How to Check Data type of a Variable in R

    When it comes to checking the data type of a variable, it depends on what…

    2 days ago

    Mastering grepl() Function in R

    The grepl() function (stands for "grep logical") in R searches for patterns within each element…

    3 days ago

    zip(), unzip() and tar(), untar() Functions in R

    The zip() function creates a new zip archive file. You must ensure that the zip tool…

    4 days ago

    How to Create a Grouped Boxplot in R

    To create a grouped boxplot in R, we can use the ggplot2 library's aes() and…

    7 days ago

    R head() and tail() Functions

    For data exploration, quickly inspecting the data, verifying the structure, or debugging large datasets, we…

    1 week ago