unlink in R: How to Delete File or Directory in R

While programming, we often need to remove the specific file or directory programmatically. In this tutorial, we will see how to remove a file or directory in R.

Delete File in R

To remove a file in R, use the unlink() function. The unlink() function deletes the file(s) or directories specified by the input argument. The unlink() function takes a maximum of three parameters and removes the specified file or directory.

The unlink(x, recursive = TRUE) function deletes the just symbolic link if the target of such a link is a directory.

Syntax of unlink() function

unlink(x, recursive = FALSE, force = FALSE)

Arguments

x: It is a character vector with the names of the file(s) or directories to be deleted. Wildcards (normally * and ?) are allowed.

recursive: It is a logical argument. Should directories be deleted recursively? If recursive = FALSE, directories are not deleted, not even empty ones. The recursive = TRUE might not be supported on all platforms when ignored, with a warning.

force: It is also a logical argument. Should permissions be changed (if possible) to allow the file or directory to be removed?

Example

Let’s remove the file from the current working directory.

To check if the file exists or not, use the file.exists() method.

file <- "data.R"

if (file.exists(file)) {
 unlink(file)
 cat("The file is deleted")
}

Output

The file is deleted

It is because the data.R file exists in the current working directory.

If you rerun the above code, you won’t get anything in return because the file is already deleted. So the if condition will not be executed.

The file.exists() method returns the logical vector indicating whether the files named by its argument exist.

How to Remove Directory in R

To remove a directory in R, use the unlink() function.

Let’s say, we have a directory called Ampol in the current working directory. It is an empty directory. Let’s remove it.

file <- "ampol"

if (file.exists(file)) {
 unlink(file)
 cat("The directory has been deleted")
}

Output

The directory has been deleted

Let’s pass recursive = TRUE to the unlink() function and see the output.

file <- "ampol"

if (file.exists(file)) {
 unlink(file, recursive = TRUE)
 cat("The directory is deleted")
}

And it will remove the directory recursively.

That is it for deleting the file or folder in R.

Leave a Comment