43

R provides two functions to remove files (and folder) from the file system:

  • unlink
  • file.remove

It's not entirely obvious what the differences are, or indeed when to use which, other than that unlink takes some additional arguments.

Reading the source code for these functions doesn't help very much, since both simply calls a compiled C function.

What are the differences? When should you use unlink in preference to file.remove, or vice versa?

3
  • you can find the implementation here: svn.r-project.org/R/trunk/src/main/platform.c
    – kohske
    Mar 27, 2012 at 11:51
  • 11
    unlink will delete directories, but file.remove will only delete empty ones, and not on Windows
    – James
    Mar 27, 2012 at 12:19
  • 8
    FYI: In R news, changes in version 2.15.0: "The behaviour of unlink(recursive = TRUE) for a symbolic link to a directory has changed: it now removes the link rather than the directory contents (just as rm -r does)."
    – GSee
    Mar 27, 2012 at 12:30

2 Answers 2

30

My guess is simply that unlink was present in S, since it references Becker, Chambers and Wilks (1988), whereas file.remove (and file.copy, file.create, etc.) have been part of R since early on in order to provide a family of functions for general file manipulation.

unlink corresponds to a very old Unix function (and certainly existed when the 1988 version of S appeared): http://en.wikipedia.org/wiki/Unlink_(Unix)

So, unlink is there for compatibility with S, file.remove is there as a part of R and both are maintained in order to support long existing code from S and R. Other than that simply choose the one that suits your needs (or habits) best.

0
9

The main practical difference in the behaviour of the functions is how they handle a file that is currently open, and thus which cannot be immediately deleted:

  • unlink() marks the file for deletion as soon as it is not open in any other context;
  • file.remove() leaves the file intact, returning FALSE, but throws a warning.

Related: how to remove the file when "permisson denied" in R?

1
  • 2
    unlink allows "globbed" filenames, file.remove() seems not to. May 20, 2022 at 18:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.