【发布时间】:2010-12-05 05:29:31
【问题描述】:
我正在尝试找到一种方法来阻止在 R 中使用 save() 和 save.image() 函数时意外覆盖文件。
【问题讨论】:
我正在尝试找到一种方法来阻止在 R 中使用 save() 和 save.image() 函数时意外覆盖文件。
【问题讨论】:
使用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(),用户可能不知道函数覆盖。
【讨论】:
正如文斯所写,您可以使用 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()。
【讨论】: