为了账号安全,请及时绑定邮箱和手机立即绑定

检查目录是否存在,如果不存在则创建

检查目录是否存在,如果不存在则创建

ibeautiful 2019-11-21 15:18:04
我经常发现自己写的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))}
查看完整描述

3 回答

?
杨魅力

TA贡献1811条经验 获得超5个赞

用途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))


查看完整回答
反对 回复 2019-11-21
?
千巷猫影

TA贡献1829条经验 获得超7个赞

随着的发布,R 3.2.0有一个名为的新功能dir.exists()。要使用此功能并创建目录(如果目录不存在),可以使用:


ifelse(!dir.exists(file.path(mainDir, subDir)), dir.create(file.path(mainDir, subDir)), FALSE)

FALSE如果目录已经存在或TRUE无法创建,并且目录不存在但创建成功,则将返回该目录。


请注意,只需检查目录是否存在,即可使用


dir.exists(file.path(mainDir, subDir))


查看完整回答
反对 回复 2019-11-21
?
翻翻过去那场雪

TA贡献2065条经验 获得超13个赞

就一般体系结构而言,我建议在目录创建方面采用以下结构。这将涵盖大多数潜在问题,并且dir.create呼叫将检测到与目录创建有关的任何其他问题。


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。


查看完整回答
反对 回复 2019-11-21
  • 3 回答
  • 0 关注
  • 1056 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信