在原始帖子中,使用file.exists()检测目录是否存在是一个问题。如果subDir包含现有文件的名称(而不仅仅是路径),file.exists()会返回TRUE,但是对setwd()的调用将失败,因为您无法将工作目录设置为指向文件。
我建议使用file_test(op="-d", subDir)来检查目录是否存在,如果subDir是现有目录,则返回"TRUE",但如果subDir是现有文件或不存在的文件或目录,则返回FALSE。同样,可以通过op="-f"检查文件是否存在。
另外,如另一条评论所述,工作目录是R环境的一部分,应该由用户控制,而不是脚本。理想情况下,脚本不应更改R环境。为解决此问题,我可能会使用options()来存储全局可用的目录,以便在其中输出所有内容。
因此,请考虑以下解决方案,其中someUniqueTag只是程序员定义的选项名称前缀,这使得具有相同名称的选项已经存在的可能性较小。(例如,如果您正在开发名为"filer"的软件包,则可以使用filer.mainDir和filer.subDir)。
以下代码将用于设置可供其他脚本稍后使用的选项(从而避免在脚本中使用setwd()),并在必要时创建文件夹:
mainDir = "c:/path/to/main/dir"
subDir = "outputDirectory"
options(someUniqueTag.mainDir = mainDir)
options(someUniqueTag.subDir = "subDir")
if (!file_test("-d", file.path(mainDir, subDir)){
if(file_test("-f", file.path(mainDir, subDir)) {
stop("Path can't be created because a file with that name already exists.")
} else {
dir.create(file.path(mainDir, subDir))
}
}
然后,在需要操作subDir中的文件的任何后续脚本中,您可以使用类似以下的内容:
mainDir = getOption(someUniqueTag.mainDir)
subDir = getOption(someUniqueTag.subDir)
filename = "fileToBeCreated.txt"
file.create(file.path(mainDir, subDir, filename))
这个解决方案使工作目录完全由用户控制。
setwd()
函数,因为它会破坏使用工作目录的原本设计意图,这样做会使你的代码难以在不同计算机间移植。 - hadley.bat
文件,最终用户将永远不需要修改它。 - Chasewrite.table(file = "path/to/output/directory", ...)
的东西来替换我的setwd()
调用吗? - Chaseout_dir <- "path/to/output/directory"
参数化,然后使用write.table(file = file.path(out_dir,"table_1.csv"), ...)
。甚至可以使用out_file <- function(fnm) file.path("path/to/output/directory", fnm)
,然后使用write.table(file = out_file("table_1.csv"), ...)
(我在使用网络驱动器时使用类似的方法)。 - Marek