我经常发现自己在编写生成大量输出的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))
    
}

当前回答

一行程序:

If (!dir.exists(output_dir)) {dir.create(output_dir)}

例子:

dateDIR <- as.character(Sys.Date())
outputDIR <- file.path(outD, dateDIR)
if (!dir.exists(outputDIR)) {dir.create(outputDIR)}

其他回答

我在R 2.15.3中遇到了一个问题,当我试图在共享网络驱动器上递归地创建一个树结构时,我会得到一个权限错误。

为了解决这个问题,我手动创建了结构;

mkdirs <- function(fp) {
    if(!file.exists(fp)) {
        mkdirs(dirname(fp))
        dir.create(fp)
    }
} 

mkdirs("H:/foo/bar")

下面是简单的检查,如果不存在就创建dir:

## Provide the dir name(i.e sub dir) that you want to create under main dir:
output_dir <- file.path(main_dir, sub_dir)

if (!dir.exists(output_dir)){
dir.create(output_dir)
} else {
    print("Dir already exists!")
}

要找出一个路径是否是一个有效的目录,请尝试:

file.info(cacheDir)[1,"isdir"]

File.info不关心结尾的斜杠。

文件。在Windows上存在的目录如果以斜杠结尾将失败,如果没有斜杠则成功。因此,这不能用于确定路径是否为目录。

file.exists("R:/data/CCAM/CCAMC160b_echam5_A2-ct-uf.-5t05N.190to240E_level1000/cache/")
[1] FALSE

file.exists("R:/data/CCAM/CCAMC160b_echam5_A2-ct-uf.-5t05N.190to240E_level1000/cache")
[1] TRUE

file.info(cacheDir)["isdir"]

Package hutils(由我编写)具有函数provider .dir(path)和provider .file(path)来检查路径上的目录/文件是否存在,如果它们不存在则创建它们。

我知道这个问题之前有人问过,但如果有用的话,here包确实有助于不必引用特定的文件路径,并使代码更具可移植性。它会自动将你的工作目录定义为你的.Rproj文件所在的目录,所以下面的文件通常就足够了,而不必定义你的工作目录的文件路径:

library(here)

if (!dir.exists(here(outputDir))) {dir.create(here(outputDir))}