1

由于我正在处理许多子目录,我觉得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()但也许有一些内置的、方便的方法?

4

2 回答 2

4

您可能希望setwd返回上一个目录,以便您可以在函数中执行以下操作:

f <- function(){
   old <- setwd( "some/where" )
   on.exit( setwd(old) )

   # do something
} 

这样,您就不会弄乱全局变量<<-等...

于 2013-11-26T09:33:12.367 回答
2

为什么不在启动时将起始目录存储为变量并使用它来重置目录:

mydir <- getwd()
# do anything
# change directories
# do more stuff
# change directories
# yadda yadda yadda
setwd(mydir)

此外,听起来您可能想要利用相对路径:

setwd('./subdir')
# do stuff, then go back:
setwd('../')
于 2013-11-26T12:19:30.247 回答