Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a directory in R?

Tags:

directory

r

After some research I found out that the following works:

unlink("mydir") 

and you have to use the recursive option in case you want to remove recursively:

unlink("mydir", recursive=TRUE) 

However, I noted that unlink("mydir") alone, without the recursive option, does not produce any output when mydir contains subdirectories: it does not remove the dirs but does not show any warning. Just nothing:

> list.dirs() [1] "."          "./r" > dir.create("test") > dir.create("test/test2") > list.dirs() [1] "."            "./r"   "./test"       "./test/test2" > unlink("test")          ######### here I would expect a warning ######### > list.dirs() [1] "."            "./r"   "./test"       "./test/test2" > unlink("test", recursive=TRUE) > list.dirs() [1] "."          "./r" 

Is there any way to get any kind of "notification", like the one you would get in UNIX systems?

$ rmdir test rmdir: failed to remove «test»: Directory not empty 

I am using R version 3.1.2 (2014-10-31). I tried playing with options(warn=1) etc but no luck.

like image 343
fedorqui 'SO stop harming' Avatar asked Jan 22 '15 19:01

fedorqui 'SO stop harming'


People also ask

How can I delete a directory?

To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.

Does rm delete directory?

Removing Directories with rm rm is a command-line utility for deleting files and directories. Unlike rmdir the rm command can delete both empty and non-empty directories. By default, when used without any option rm does not remove directories.


2 Answers

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.

like image 147
zw324 Avatar answered Oct 13 '22 21:10

zw324


Simply

unlink("mydir", recursive = TRUE) # will delete directory called 'mydir' 
like image 25
stevec Avatar answered Oct 13 '22 20:10

stevec