【问题标题】:Control working directory within a function that is aborted in R在 R 中中止的函数中控制工作目录
【发布时间】:2017-07-30 11:21:11
【问题描述】:

我有一个执行大量重复计算的函数,在某些时候,它会将结果导出到由该函数创建的工作目录中。该函数的方案如下所示:

fun <- function (..., path){
# 1. create directory specified in the path argument
# 2. set directory from 1. as a working directory via setwd () function
# 3. do calculations
# 4. as 3. proceeds, the function exports results (several lists) in the new working directory
}

有时,我需要在第 3 阶段中止函数。(例如,在函数已经创建并设置工作目录并可能将部分结果导出到工作目录之后)。

问题:是否有可能编写一个函数,如果它在第 3 阶段手动中止,该函数会将工作目录设置为执行该函数之前的状态(例如系统默认工作目录)?

【问题讨论】:

    标签: r performance output


    【解决方案1】:

    你可以使用on.exit()

    所以在代码的开头,使用home_dir &lt;- getwd() 存储工作目录,然后直接调用on.exit(setwd(home_dir))。希望这会有所帮助!


    例子:

    testfun <- function()
    {
      home_dir <- getwd()
      on.exit(setwd(home_dir))
      setwd(dirname(getwd()))
    }
    
    getwd()
    
    testfun()
    
    getwd()
    

    两个getwd() 语句将返回相同的工作目录,因为虽然它在testfun 中更改为dirname(getwd()),但它被on.exit() 中的on.exit() 调用重置

    【讨论】:

      猜你喜欢
      • 2017-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-20
      相关资源
      最近更新 更多