How to remove a directory in R?

Simply

unlink("mydir", recursive = TRUE) # will delete directory called 'mydir'

Here's a wrapper function for you if you really need to see an error msg:

.unlink <- function(x, recursive = FALSE, force = FALSE) {
  if (unlink(x, recursive, force) == 0)
    return(invisible(TRUE))
  stop(sprintf("Failed to remove [%s]", x))
}

See help ?unlink:

Value

0 for success, 1 for failure, invisibly. Not deleting a non-existent file is not a failure, nor is being unable to delete a directory if recursive = FALSE. However, missing values in x are regarded as failures.

In the case where there is a folder foo the unlink call without recursive=TRUE will return 1.

Note that actually the behavior is more like rm -f, which means that unlinking a non-existent file will return 0.

Tags:

Directory

R