To delete file in R, you can use file.remove() or unlink() function.

The following methods show how you can do it with syntax.

Method 1: Use file.remove() Function

file.remove("file_path")

Method 2: Use unlink() Function

unlink("file_path")

The following examples show how we remove file in R using two different functions.

Using file.remove() Function

Let’s see how we can use file.remove() function to delete file in R:

# Define file to delete
file1  <- "sample.txt"

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

Output:

File deleted

From output we can say file is deleted successfully.

Let’s see how we can delete file using unlink() function in R:

# Define file to delete
file1  <- "sample1.txt"

# Delete file if it exists
if (file.exists(file1)) {
  unlink(file1)
  cat("File deleted")
} else {
  cat("No file found")
}

Output:

File deleted

Here the output shows file deleted.