How to Delete a File Using R (With Example)

Using the R programming language, you can delete a file by using the file.remove() command. For example, to delete a file named ‘myfile.txt’, you would type: file.remove(“myfile.txt”) into the R console. This will delete the file from the specified directory. Be sure to check the directory to make sure that the file has been successfully deleted.


You can use the following syntax to delete a file in a specific location using R:

#define file to delete
this_file  <- "C:/Users/bob/Documents/my_data_files/soccer_data.csv"

#delete file if it exists
if (file.exists(this_file)) {
  file.remove(this_file)
  cat("File deleted")
} else {
  cat("No file found")
}

This particular syntax attempts to delete a file called soccer_data.csv located in the following folder:

C:/Users/bob/Documents/my_data_files

If the file exists, the file.remove() function deletes the file and uses the function to output the message “File deleted” to the console.

If the file does not exist, then the cat function outputs the message “No file found” to the console.

The following example shows how to use this syntax in practice.

Example: Delete a File Using R

Suppose we want to delete a file called soccer_data.csv located in the following folder:

C:/Users/bob/Documents/my_data_files

The folder currently has three files in it:

We can use the following syntax in R to delete this file if it exists:

#define file to delete
this_file  <- "C:/Users/bob/Documents/my_data_files/soccer_data.csv"

#delete file if it exists
if (file.exists(this_file)) {
  file.remove(this_file)
  cat("File deleted")
} else {
  cat("No file found")
}

File deleted

 We receive the message “File deleted” which tells us that the file has been deleted.

If we return to the folder where the file used to exist, we can see that it indeed has been deleted:

The following tutorials explain how to perform other common tasks in R:

x