2017-07-02 45 views
-1

我想输出我的数据到一个pdf中,我希望这个pdf的文件名可以自动检测并递增。我的代码如下:R pdf自动检测并增加文件名称

for (i in 1:3){ 
    pdf("E:/pdf%03d.pdf", onefile=T) 

    x <- runif(100) 
    y <- rnorm(100) 

    plot(x, y) 
    plot(x, sin(y)) 

    graphics.off() 
} 

我希望得到三个pdf,但实际上我只能得到一个。那么代码中的错误在哪里?提前致谢!

回答

0

像这样的事情sprintf("E:/pdf%03d.pdf", i)

#' Sequential file naming 
#' 
#' @param ptn string that includes a [base::sprintf()] format string for an 
#' integer, either `%d` or `%03d`; for example, `"filename-%03d.pdf"` 
#' @param full.names logical, passed to [base::files()] 
#' @return character, representing a filename that did not exist the 
#' moment the function was called; NB: there is a potential 
#' race-condition here 
#' @md 
#' @example 
#' \dontrun{ 
#' ### starts at 1 for non-existent files 
#' sequentialFilename("does-not-yet-exist-%d.pdf") 
#' # [1] "does-not-yet-exist-1.pdf" 
#' sequentialFilename("does-not-yet-exist-%05d.pdf") 
#' # [1] "does-not-yet-exist-00001.pdf" 
#' 
#' ### empty files, please do not blame me if you over-write pre-existing files! 
#' writeLines("", "fn-001") 
#' writeLines("", "fn-002") 
#' sequentialFilename("fn-%03d") 
#' # [1] "fn-003" 
#' 
#' ### finds the max, not the next unused 
#' writeLines("", "fn-100") 
#' sequentialFilename("fn-%03d") 
#' # [1] "fn-101" 
#' 
#' ### can extend beyond the patterned number 
#' writeLines("", "fn-1000") 
#' sequentialFilename("fn-%03d") 
#' # [1] "fn-1001" 
#' } 
sequentialFilename <- function(ptn, full.names = FALSE) { 
    if (! nchar(gsub("[^%]", "", ptn)) == 1L || 
     ! grepl("%[0-9]*d", ptn)) 
    stop("'ptn' must contain exactly one '%' sprintf formatting string") 
    # extract the numbering portion, to convert into a filename glob 
    gre <- gregexpr("%[0-9]*d", ptn) 
    # escape globbing characters 
    glob <- gsub("([.*?])", "\\\\\\1", ptn) 
    regmatches(glob, gre) <- "[0-9]+" 
    files <- list.files(pattern = glob, full.names = full.names) 
    # find the highest used numbered filename 
    highestnumber <- 
    if (! length(files)) { 
     0 
    } else { 
     prepost <- regmatches(ptn, gre, invert = TRUE)[[1L]] 
     max(as.integer(
     mapply(substr, files, 
       1 + nchar(prepost[1]), nchar(files) - nchar(prepost[2])) 
    ), 0, na.rm = TRUE) 
    } 
    if (is.na(highestnumber)) 
    stop("something went wrong, could not find the next number") 
    nextfile <- sprintf(ptn, highestnumber + 1) 
    browser() 
    if (file.exists(nextfile)) 
    stop(paste("oops, the next-numbered file already exists ...", 
       sQuote(nextfile)), call. = FALSE) 
    nextfile 
} 

警告emptor:我的测试很少,请注意在生产中使用它。

+0

谢谢!你的代码工作正常! – Lin

1

pdf

+0

谢谢!我的代码只是一个测试。我的目的是自动检测pdf的存在,然后增加文件名。 – Lin