[英]Dir.create function in R erases files in parent folders on the computer
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. 如果该文件夹不存在,则应该在父文件夹“ R”中创建一个名为“ Sample”的文件夹,并使用新文件夹替换该文件夹(如果存在)。
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").
昨天,我使用此代码尝试创建一个“ Sample”文件夹中未预先存在的文件夹(例如“ 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.
它没有创建名为“ Plots”的文件夹,而是检测到存在父文件夹“ Sample”,并开始删除该文件夹中包含的每个文件。 Afterwards, it proceeded to delete all of the files in the upper folder - "R" - as well.
然后,它继续删除上层文件夹“ R”中的所有文件。 I had to cancel the code before it deletes my (D:) drive.
我必须先取消代码,然后才能删除(D :)驱动器。
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. 正如@ytk在上面的注释中指出的那样,在第一个
if
语句中对make.dir
的调用使函数变得疯狂了。 Removing that solved the problem. 删除即可解决问题。 Thanks, ytk
谢谢,ytk
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.