How to Create Files and Directories in R

Creating a folder and file programmatically is one of the most important operations in programming. R has many inbuilt functions that can help you perform file operations. Let’s see how to create files and directories in R.

How to Create a directory  in R

To create a directory in R, use the dir.create() method. The dir.create() method accepts a folder generated in the current working directory or specifies a path. Before working with files, it’s a better idea to know what directory you’re working in. In R, you can figure out which directory you are working on the getwd() function.


dir.create(path, showWarnings = TRUE, recursive = FALSE, mode = "0777")


path: It is a character vector containing a single path name.

paths: They are character vectors containing file or directory paths.

showWarnings: It is a logical argument; should the warnings on failure be shown?

recursive: It is a logical argument. Should elements of the path other than the last be created? If true, like the Unix command mkdir -p.

mode: It will be used on Unix-alikes: it will be coerced by as.octmode. For Sys.chmod, it is recycled along paths.

Return Value

The dir.create() function returns an invisibly logical vector indicating if the operation succeeded for each of the files attempted.


Before creating a folder in R, you need to check if the same-named folder exists. To check if the folder exists, use the file.exists() method. Then if it does not exist, you can create a folder.

folder <- "mortalkombat"

if (file.exists(folder)) {

 cat("The folder already exists")

} else {



If the folder does not exist, then it will create a new directory for you.

Trailing path separators are discarded. On Windows, drives are allowed in the path specification, and unless the path is rooted, it will be interpreted relative to the current directory on that drive. The mode is ignored on Windows.

How to Create a file in R

To create a file in R programmatically, use 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.


file.create(…, showWarnings = TRUE)


…, file1, file2: They are character vectors containing file names or paths.


file <- "dataframe.R"

if (file.exists(file)) {

 cat("The file already exists")

} else {




[1] TRUE

It returns TRUE that means the file is created. Case-insensitive file systems are the norm on Windows and macOS but can be found on all OSes.

That is it for creating files and directories in R.

Leave a Comment