How to Delete a File Using R (With Example)


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 cat 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:

To delete a different file, simply change the file path specified in the variable called this_file.

Additional Resources

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

How to Import CSV Files into R
How to Import Excel Files into R
How to Import Zip Files into R

Leave a Reply

Your email address will not be published. Required fields are marked *