由于我正在处理许多子目录,我觉得setwd()
很不方便,因为它要求我记住当前和以前的位置,并在每次执行不同的分析时将它们改回来。当某些路径需要是相对路径和其他绝对路径时,事情会变得更加复杂。我正在寻找一种方便的方法来对特定代码部分应用更改,例如在 Ruby 中:
Dir.chdir("newDir") do
# some code here #
end
我写了这么丑陋的函数:
path = list()
tempDirNew <- function(..., abs= FALSE){
path$tempDir$old <<- getwd()
mod = ifelse(abs == TRUE,
'',
path$tempDir$old)
path$tempDir$new <<- file.path(mod, ...)
dir.create(path= path$tempDir$new, showWarnings= FALSE)
setwd(dir= file.path(path$tempDir$new))
}
tempDirOld <- function(){
setwd(dir= path$tempDir$old)
path$tempDir$new <- NULL
path$tempDir$old <- NULL
}
并在代码的每个部分tempDirNew('newdir')
之前和之后应用。tempDirOld()
但也许有一些内置的、方便的方法?