【问题标题】:Preventing overwriting of files when using save() or save.image()使用 save() 或 save.image() 时防止覆盖文件
【发布时间】:2010-12-05 05:29:31
【问题描述】:

我正在尝试找到一种方法来阻止在 R 中使用 save() 和 save.image() 函数时意外覆盖文件。

【问题讨论】:

    标签: r file


    【解决方案1】:

    使用file.exists() 测试文件是否存在,如果存在,则在名称后面附加一个字符串。

    编辑:

    谢谢 Marek,我会稍微扩展一下你的想法...他可以添加这个来处理 save()save.image()

    SafeSave <- function( ..., file=stop("'file' must be specified"), overwrite=FALSE, save.fun=save) {
      if ( file.exists(file) & !overwrite ) stop("'file' already exists")
      save.fun(..., file=file)
    }
    

    我不会覆盖保存...如果在 REPL 会话中使用source(),用户可能不知道函数覆盖。

    【讨论】:

    • 有谁知道如何创建一个对话框来通知用户要写入的文件已经存在?用户可能只是在不知情的情况下关闭了 R 会话,并且没有保存任何内容。
    【解决方案2】:

    正如文斯所写,您可以使用 file.exists() 来检查是否存在。

    我建议替换原来的save函数:

    save <- function( ..., file=stop("'file' must be specified"), overwrite=FALSE ) {
      if ( file.exists(file) & !overwrite ) stop("'file' already exists")
      base::save(..., file=file)
    }
    

    您可以编写类似的代码来替换 save.image()

    【讨论】:

      猜你喜欢
      • 2012-05-13
      • 1970-01-01
      • 2012-11-04
      • 1970-01-01
      • 2015-08-26
      • 2014-05-26
      • 1970-01-01
      • 2017-05-09
      • 1970-01-01
      相关资源
      最近更新 更多