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, ie 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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.