3 回答

TA貢獻1811條經驗 獲得超6個贊
用途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))

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

TA貢獻2065條經驗 獲得超14個贊
就一般體系結構而言,我建議在目錄創建方面采用以下結構。這將涵蓋大多數潛在問題,并且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。
- 3 回答
- 0 關注
- 1239 瀏覽
添加回答
舉報