如何覆盖在R中的函数中创建的文件夹? 背景

如何覆盖在R中的函数中创建的文件夹? 背景,r,function,R,Function,我有一个名为BP(参见下面的R代码)的函数。此函数:(1)创建一个文件夹。(2) 将文件夹设置为工作目录。(3) 创建两个绘图。(4) 将每个绘图保存为(1)中创建的文件夹中的png文件 问题: 如果我运行此函数超过1次,我会收到以下错误消息: 警告消息: 在dir.create(x)中:“C:\Users\…\Documents\Animation”已存在 如何让此功能“覆盖”每次运行后创建的上一个文件夹? BP = function(){ ##########################

我有一个名为
BP
(参见下面的R代码)的函数。此函数:(1)创建一个文件夹。(2) 将文件夹设置为工作目录。(3) 创建两个绘图。(4) 将每个绘图保存为(1)中创建的文件夹中的
png
文件

问题: 如果我运行此函数超过1次,我会收到以下错误消息:
警告消息:
在dir.create(x)中:“C:\Users\…\Documents\Animation”已存在

如何让此功能“覆盖”每次运行后创建的上一个文件夹?

BP = function(){
################################       # set working directory to "home"
setwd("~")
x <- paste0(getwd(), "/", "Animation") # Define the path & name of a new folder
dir.create(x)                          # create the new folder with name above
setwd(x)                               # set this just created folder as Work.Direc.

################################       # Create two plots save them as png in the above 
                                       # folder
for(i in 1:2) {

png(paste0("plot_", i, ".png"), width = 1200, height = 1300, res = 200)

plot( rnorm(1e2) )

dev.off()

   }

}

## Test Here:
BP()
BP=function(){
#################################将工作目录设置为“主目录”
setwd(“~”)

x您不需要每次调用函数时都创建新文件夹。请使用
文件检查文件夹是否存在。存在
(尽管其名称也适用于文件夹)。仅在文件夹不存在时创建文件夹

如果需要在每次函数调用中清空文件夹,可以使用

file.remove(list.files(x, full.names = TRUE))