解决此问题的方法是使用on.exit获取临时文件并将它们保存在不同的目录中。一个示例函数如下所示:
ranfunction <- function(){
#Get list of files in tempdir
on.exit(templist <- list.files(tempdir(), full.names = T,pattern = "^file") )
#create a new directory for files to go on exit
#use add = T to add to the on.exit call
on.exit(dir.create(dir1 <- file.path("G:","testdir")),add = T )
#for each file in templist assign it to the new directory
on.exit(
lapply(templist,function(x){
file.create(assign(x, tempfile(tmpdir = dir1) ))})
,add=T)
}
ranfunction()
Run Code Online (Sandbox Code Playgroud)
该函数没有考虑到的一件事是,如果您重新运行它,它将抛出一个错误,因为新目录dir1已经存在。您必须dir1在重新运行脚本之前删除。