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

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

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

函数式编程 2020-02-04 15:17:02
我经常发现自己写的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贡献1830条经验 获得超9个赞

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


查看完整回答
反对 回复 2020-02-04
?
幕布斯6054654

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

自2015年4月16日起,随着的发布,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))


查看完整回答
反对 回复 2020-02-04
?
RISEBY

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

就一般体系结构而言,我建议在目录创建方面采用以下结构。这将涵盖大多数潜在的问题,并且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。


查看完整回答
反对 回复 2020-02-04
  • 3 回答
  • 0 关注
  • 656 浏览

添加回答

举报

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