When working with file systems, checking the directory or file existence is always better before commencing the operations.
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.
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")
}
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.
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.
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")
}
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!
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
Whether you are reading or writing files via programs in the file system, it is…
When it comes to checking the data type of a variable, it depends on what…
The grepl() function (stands for "grep logical") in R searches for patterns within each element…
The zip() function creates a new zip archive file. You must ensure that the zip tool…
To create a grouped boxplot in R, we can use the ggplot2 library's aes() and…
For data exploration, quickly inspecting the data, verifying the structure, or debugging large datasets, we…