【问题标题】:How to overwrite a folder on the computer using functions in R如何使用 R 中的函数覆盖计算机上的文件夹
【发布时间】:2016-11-17 10:27:43
【问题描述】:

我正在尝试在我的脚本中实现一个代码,该代码将在我的计算机上创建一个新文件夹并将绘图保存到其中,使用:

daily <- "D:/Work/R/Daily"
dir.create(daily)
for (d in unique(data.air$yr_day)) {
 mypath <- file.path(daily, paste(name, d, ".png", sep = "" )) 
 png(filename = mypath, width = 963, height = 690) 
 timePlot(subset(data.air, yr_day == d), 
       plot.type = "p",
       y.relation = y.scale,
       pollutant = c("co2.ppm", "o2.permeg", "apo"), 
       date.pad = TRUE,
       pch = c(19,19,19),
       cex = 0.2,
       xlab = paste("Time of day in hours on", d),
       ylab = "CO2, O2, and APO concentrations",
       name.pol = c("CO2 (ppm)", "O2 (per meg)", "APO (per meg)"),
       date.breaks = 24,
       date.format = "%H:%M"
  )
 dev.off()
}

但是,在第一次运行之后,每当我再次运行代码时,该函数都不会覆盖旧文件夹和其中的绘图,而是返回此错误:

Warning message:
In dir.create(daily) : 'D:\Summer Work with Andrew\R\Daily' already exists

那么我该如何更改代码,以便每次我再次运行代码时它都会用新的图/文件夹覆盖旧的图/文件夹?

谢谢

【问题讨论】:

  • 您不需要每次都覆盖文件夹。您可以在顶部添加:if(!file.exists(daily)) dir.create(daily)。这将创建 daily 文件夹,前提是它尚不存在。绘图会自动覆盖。
  • @ytk 添加您的调整消除了警告消息,但是,绘图似乎没有被覆盖(我检查了创建的日期,它是旧日期)
  • 测试目录是否存在是dir.create 已经做的事情。要看不到警告,请使用dir.create(path, showWarnings = FALSE)。如果要删除目录中的所有内容,可以unlink(dir)before调用dir.create(dir)
  • @Ulrik 谢谢你,我已经成功了

标签: r directory overwrite


【解决方案1】:

感谢 cmets 的建议,我已经设法解决了这个问题。 为了简化工作以供将来使用,我创建了一个新函数来完成@Ulrik 在上面评论中所说的工作:

make.dir <- function(fp) {
if(!file.exists(fp)) {  # If the folder does not exist, create a new one
make.dir(dirname(fp))
dir.create(fp)
} else {   # If it existed, delete and replace with a new one  
unlink(fp, recursive = TRUE)
dir.create(fp)
  }
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-29
    • 2013-10-29
    • 1970-01-01
    • 2018-05-16
    • 2020-03-23
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多