How to Delete File or Directory in R?

To delete a file or directory in R use unlike() or file.remove() functions. While working in R programming we are often required to delete a file(s) or a directory(s) after loading the data. By using these functions, we can delete a single file, multiple files, all files in a directory, sub-directories e.t.c.

Related: How to Rename file in R?

1. Quick Examples of Delete File or Directory

The following are quick examples of how to delete a file, multiple files, directories, and sub-directories recursively.


# Delete File
unlink("file_name.csv")

# Delete Multiple Files
unlink(c("file1","file2"))

# Delete Dir
unlink("dir",recursive = TRUE)

# Delete all files in a directory
unlink("/direcory/path/*")

# Delete only CSV files in a directory
unlink("/direcory/path/*.csv")

# Using file.remove()

file_path <- '/file/path/'

# Get all files in the directories, recursively
f <- list.files(file_path, include.dirs = F, full.names = T, recursive = T)

# remove the files
file.remove(f)

# Use Patterns to remove files
mydir <- "/folder/to/remove"
files_to_delete <- dir(path=mydir ,pattern="*.csv"))
file.remove(file.path(mydir, files_to_delete))

2. Using unlink() To Delete File or Directory

In this section let’s learn the syntax of unlink(), the parameters it takes and some examples of how efficiently we can delete a file, a directory, sub-directories recursively e.t.c. Below are the key points to note while using the unlink() function to remove a file or a directory in R.

  1. It also supports wildcard characters and character classes such as [a-z].
  2. If a file or directory doesn’t exit, it won’t fail.
  3. Returns 0 for success, 1 for failure.
  4. unlink(x, recursive = TRUE) deletes the just symbolic link if the target of a link is a directory.
  5. If recursive = FALSE directories are not deleted, not even empty ones.
  6. To delete a directory you have to use recursive = TRUE
  7. Windows cannot remove the current working directory or any file that is already opened by any process.

2.1 Syntax of unlink()

Following is the syntax of the unlink() function.


# syntax of unlink()
unlink(x, recursive = FALSE, force = FALSE)

Parameters:

  • x: It is a character vector with the files or directories you wanted to delete. It also accepts wildcard (* and ?).
  • recursive: Accepts TRUE/FALSE. Use TRUE to delete directories recursively
  • force: Accepts TRUE/FALSE. Deletes file/directory by changing permissions.

3. Delete File in R

Use the R base function unlink() to delete a file from the current working directory. You can also specify the absolute or relative path if you wanted to delete a file from any specified location. Here I have used file.exists() to check if a file exists before deleting the file.

The file.exists() method returns the logical vector indicating whether the specified file exists in the path or not. It is not necessary to check if a file exists or not but it is a good practice.


# Delete file
file_name <- "data_file.txt"

if (file.exists(file_name)) {
 unlink(file_name)
 print("File is deleted..")
} else{
 print("File not exists..")
}

4. Delete Multiple Files

When you wanted to delete multiple files in R at a time, pass all the file names in an R vector to the unlink() function. This deletes all specified files. To create a vector use c() function.


# Delete Multiple Files
unlink(c("file1","file2"))

5. Delete Directory in R

To delete a directory/folder recursively (all sub-directories) in R use unlink() function. The following example deletes the directory named ‘directory_to_remove’ and its subdirectories from the current working directory. Specify the absolute or relative path in order to remove it from any location.


# Delete Directory
dir <- "directory_to_remove"

if (file.exists(dir)) {
 unlink(dir,recursive = TRUE)
 cat("Directory has been deleted")
}

6. Delete All Files in a Directory

Use wildcard character * to delete all files in a directory or by pattern matching. The first example from below deletes all files but doesn’t delete any folder if exists. The second example deletes all files that have the extension .csv.


# Remove all files in a directory
unlink("/direcory/path/*")

# Remove only CSV files in a directory
unlink("/direcory/path/*.csv")

7. Delete Folders by Force

The following example deletes all files and directories in a folder recursively by force after changing the file permissions.


# Remove folder recursively
unlink('/folder/to/delete', recursive = TRUE, force = TRUE)

8. Using file.remove()

Let’s finally use file.remove() function in R to remove files and folders, the following example removes all the files in a folder and its sub folders.


file_path <- '/file/path/'

# Get all files in the directories, recursively
f <- list.files(file_path, include.dirs = F, full.names = T, recursive = T)

# remove the files
file.remove(f)

9. Use Pattern to Remove File

The following R example deletes or removes all matched files from a directory. Here, using pattern with dir() to make sure only desired files will be selected to remove.


# Use Patterns to remove files
mydir <- "/folder/to/remove"
files_to_delete <- dir(path=mydir ,pattern="*.csv"))
file.remove(file.path(mydir, files_to_delete))

10. Conclusion

In this article, you have learned how to delete a file or delete a directory in R programming language by using unlink() and file.remove() functions. By using these you can remove a single file, all files, directories, and subdirectories.

Related Articles

References

r delete file

NNK

SparkByExamples.com is a Big Data and Spark examples community page, all examples are simple and easy to understand and well tested in our development environment Read more ..

Leave a Reply

You are currently viewing How to Delete File or Directory in R?