我经常发现自己在编写生成大量输出的R脚本。我发现把这个输出放到它自己的目录中更干净。我下面所写的内容将检查是否存在一个目录并移动到其中,或者创建一个目录然后移动到其中。有没有更好的解决办法?
mainDir <- "c:/path/to/main/dir"
subDir <- "outputDirectory"
if (file.exists(subDir)){
setwd(file.path(mainDir, subDir))
} else {
dir.create(file.path(mainDir, subDir))
setwd(file.path(mainDir, subDir))
}
使用showWarnings = FALSE:
dir.create(file.path(mainDir, subDir), showWarnings = FALSE)
setwd(file.path(mainDir, subDir))
如果目录已经存在,Dir.create()不会崩溃,它只是打印出一个警告。所以如果你能忍受看到警告,那么这样做是没有问题的:
dir.create(file.path(mainDir, subDir))
setwd(file.path(mainDir, subDir))
在通用架构方面,我推荐以下关于目录创建的结构。这将涵盖大多数潜在的问题,而与目录创建有关的任何其他问题将由dir检测到。创建调用。
mainDir <- "~"
subDir <- "outputDirectory"
if (file.exists(paste(mainDir, subDir, "/", sep = "/", collapse = "/"))) {
cat("subDir exists in mainDir and is a directory")
} else if (file.exists(paste(mainDir, subDir, sep = "/", collapse = "/"))) {
cat("subDir exists in mainDir but is a file")
# you will probably want to handle this separately
} else {
cat("subDir does not exist in mainDir - creating")
dir.create(file.path(mainDir, subDir))
}
if (file.exists(paste(mainDir, subDir, "/", sep = "/", collapse = "/"))) {
# By this point, the directory either existed or has been successfully created
setwd(file.path(mainDir, subDir))
} else {
cat("subDir does not exist")
# Handle this error as appropriate
}
还要注意,如果~/foo不存在,则调用dir.create('~/foo/bar')将失败,除非指定recursive = TRUE。