3 回答

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超6個(gè)贊
用途showWarnings = FALSE:
dir.create(file.path(mainDir, subDir), showWarnings = FALSE)
setwd(file.path(mainDir, subDir))
dir.create()如果該目錄已存在,則不會(huì)崩潰,它只會(huì)打印出警告。因此,如果您可以看到警告,那么這樣做就沒有問題:
dir.create(file.path(mainDir, subDir))
setwd(file.path(mainDir, subDir))

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超7個(gè)贊
隨著的發(fā)布,R 3.2.0有一個(gè)名為的新功能dir.exists()。要使用此功能并創(chuàng)建目錄(如果目錄不存在),可以使用:
ifelse(!dir.exists(file.path(mainDir, subDir)), dir.create(file.path(mainDir, subDir)), FALSE)
FALSE如果目錄已經(jīng)存在或TRUE無法創(chuàng)建,并且目錄不存在但創(chuàng)建成功,則將返回該目錄。
請(qǐng)注意,只需檢查目錄是否存在,即可使用
dir.exists(file.path(mainDir, subDir))

TA貢獻(xiàn)2065條經(jīng)驗(yàn) 獲得超14個(gè)贊
就一般體系結(jié)構(gòu)而言,我建議在目錄創(chuàng)建方面采用以下結(jié)構(gòu)。這將涵蓋大多數(shù)潛在問題,并且dir.create呼叫將檢測(cè)到與目錄創(chuàng)建有關(guān)的任何其他問題。
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
}
另請(qǐng)注意,如果~/foo不存在,則dir.create('~/foo/bar')除非您指定,否則對(duì)的調(diào)用將失敗recursive = TRUE。
- 3 回答
- 0 關(guān)注
- 1231 瀏覽
添加回答
舉報(bào)