使用file.exists()来测试,如果该文件是存在的,如果是,追加一个字符串的名字.
编辑:
由于马立克,我将你的想法扩大一点......他可以添加此同时处理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)
}
Run Code Online (Sandbox Code Playgroud)
我不会覆盖保存...如果source()在REPL会话中使用,用户可能不知道函数覆盖.
正如文斯所写,你可以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)
}
Run Code Online (Sandbox Code Playgroud)
你可以写类似于替换save.image().