阻止R覆盖图形文件

时间:2014-05-26 03:31:12

标签: r graphics

我在iPad上以批处理模式使用R,并将图形文件放在〜/ Dropbox中,然后在那里查看。当我运行R的连续会话时,它会覆盖先前运行产生的图形文件,即使我使用

png(filename="Rplot%03d.png")

是否可以让R继续递增文件名?例如,如果我有Rplot001.pngRplot005.png,我希望下一个文件进入Rplot006.png

我知道可以使用png()paste()调用创建随机前缀,但我想使用我正在处理的特定项目来命名它们。

由于

1 个答案:

答案 0 :(得分:0)

您可以检测到最新的文件,并从那里开始增量。类似的东西:

串行运行

projectPng <- function(projectName, dir, ...) {
  # get a list of existing plots for the project
  plots <- list.files(path=dir, pattern=paste0(projectName, "*.png"))
  # pull out numeric component of the plot files
  nums <- as.numeric(gsub(paste("Rplots", ".png", sep="|"), "", plots))
  last <- max(nums)
  # Create a new file name with an incremented counter.
  newFile <- paste0(projectName, sprintf("%03d", last + 1), ".png")
  # now call png
  png(file.path(dir, newFile), ...)
}

现在projectPng将打开一个新设备,其中包含项目的下一个递增编号:

# If Rplots005.png exists, will open Rplots006.png
projectPng("Rplots", "~/Dropbox")

多个并行运行

或者,如果您并行运行多个运行,则可以存储全局计数器,以最小化打开新设备时每个独立运行的冲突:

projectPng <- function(projectName, dir, ...) {
  # Get the most recently opened device number as stored by `projectPng`
  counterFile <- file.path(dir, paste0(projectName, "_png_counter.txt")
  new <- tryCatch({
    last <- scan(file=counterFile, what=integer())
    cat(last + 1, "\n", file=counterFile)
    return(last + 1)
  }, error = function(e) {
    # If we're unable to open the counter file, assume no plots exist yet
    cat(1, "\n", file=counterFile)
    return(1)
  })
  # Create a new file name with an incremented counter.
  newFile <- paste0(projectName, sprintf("%03d", new), ".png")
  # now call png
  png(file.path(dir, newFile), ...)
}

但是:这不保证是安全的:如果两个R会话同时调用projectPng,则他们有可能从{{{{}}获得相同的数字1}},在另一个有机会增加计数器之前。

相关问题