0

For working purpose, I have made a new function which automatically tests whether a folder (with its name specified by its file path) exists or not:

make.dir <- function(fp) {

# If not existing, create a new one
if(!file.exists(fp)) {
make.dir(dirname(fp))
dir.create(fp, recursive = FALSE, showWarnings = FALSE)
} else {

# If existed, delete and replace with a new one  
unlink(fp, recursive = FALSE)
dir.create(fp)
 }
}

An example would be:

make.dir("D:/Work/R/Sample")

this is supposed to create a folder named "Sample" in the parental folder "R" if that folder did not exist, and replace the folder with a new one, if existed.

However, I have only been trying this with the latter case, i.e. replacing existing folders. Yesterday, I used this code to try to make a folder that did not pre-exist in "Sample" folder (say "Plots"). Instead of creating a folder named "Plots", it detected that the parent folder - "Sample" existed and started to delete every files contained in that folder. Afterwards, it proceeded to delete all of the files in the upper folder - "R" - as well. I had to cancel the code before it deletes my (D:) drive.

It works fine for replacing existing folders, but not with creating new folders. Anyone has any ideas on how to fix the function, or make a new one?

Thanks

Tung Linh
  • 321
  • 1
  • 2
  • 16
  • 1
    Your function doesn't seem to be defined correctly. Why are you calling `make.dir` in the first `if` statement? – ytk Jul 29 '16 at 13:49
  • @ytk I was following the answer from this thread (the last one) http://stackoverflow.com/questions/4216753/check-existence-of-directory-and-create-if-doesnt-exist – Tung Linh Jul 29 '16 at 13:50
  • Quite blindly, I guess. Now that you pointed that out, I might try my function again without the abnormal call – Tung Linh Jul 29 '16 at 13:51
  • @ytk Thanks for pointing out my silly mistake. It seems to be working now that I have removed that line. – Tung Linh Jul 29 '16 at 13:57
  • But do you have any idea on why it proceeds to delete parental folders/files? Is it simply a malfunction? – Tung Linh Jul 29 '16 at 13:58
  • I'm not sure, sorry. It shouldn't delete higher level folders. Can you try in a new R session? – ytk Jul 29 '16 at 14:00
  • I have been restarting R sessions and my computer, plus reinstalling R but it still delete higher level folders. I guess it's malfunctioned. Glad that it's not anymore, thanks for your help! – Tung Linh Jul 29 '16 at 14:05

1 Answers1

0

As pointed out by @ytk in the comment above, the call for make.dir in the first if statement makes the function go wild. Removing that solved the problem. Thanks, ytk

Tung Linh
  • 321
  • 1
  • 2
  • 16