Search code examples
runlink

Remove a directory in R invoking linux commands


I am writing code using R that invokes Linux commands to create a directory with multiple files which has to be deleted at the end.

I tried using file.remove(directory_name) which removed the directory only when its empty. If the directory has files, file.remove didn’t work. unlink(directory_name) didn't remove the directory.

My code:

dir.create("./dir1")  
dir.create("./dir2")  
............  
............  
............  
file.remove("./dir1")  
unlink("./dir1, recursive = TRUE")  

file.remove() threw an error:

cannot remove file './dir1', reason 'Directory not empty'.

while, unlink() didn't remove the directory.

How do I delete a directory with files in it?


Solution

  • To unlink recursively, you need to pass the recursive = TRUE as an additional parameter:

    This:

     unlink("./dir1", recursive = TRUE)  
    

    Not this:

    unlink("./dir1, recursive = TRUE")