How to specify figure names when `knit`ting with` fig.keep = 'all'`

I use knitrto create reports. However, I often first prepare "internal" documents that contain all the graphs, and then for the final report or paper I want to include only some numbers.

Let's say I have a set of systematically created shapes, let's say I iterate over my instance:

<<sample, fig.keep = 'all'>>=
specimen <- c("436a", "783a", "10b")
for (s in specimen) # in reality it would e.g. be levels (specimen)
   plot (results [s])
@

This will create multiple files figures/sample1.pdf, figures/sample2.pdfetc. Although numbering with 1, 2, ... is good for a report created by a scratch, if I want to include one of the graphs in a document, it is cumbersome and error prone to figure out which .pdf belongs to which sample.

How can I say knitruse file names for example "figures/sample-436a.pdf"?

I tried <<fig.path = sprintf ("figures/sample-%s", s)>>=, but it does not work: sit is unknown, so I think it fig.pathis evaluated at the beginning of fragment processing, and not when saving the fragment.

PS: One obvious way to reduce the risk of mistakes is to name them, but IMHO they are ugly in paper.

+5
source share
2 answers
Good question. Not sure if this could be a satisfactory answer:
\documentclass{article}

\begin{document}

<<prepare-src, include=FALSE>>=
s = names(iris)[-5]
# construct the source document
src = sprintf('<<sample-%s>>=
hist(iris[,"%s"], col="gray", border="white")
@', s, s)
@

% evaluate the source
\Sexpr{knit(text = src)}

\end{document}

In your case, you only need to decide which instance is included in s.

+5
source

( ) , . , , chunk fig.names , . , knitr, asis.

\documentclass{article}
\begin{document}

<<main, echo = F>>=
knit_hooks$set(fig.names = function(before, options, envir){
  if (!before) {
    from = dir('figure', pattern = opts_current$get('label'), full = TRUE)
    to = sprintf('%s.pdf', file.path('figure', 
      paste(opts_current$get('label'), options$fig.names, sep = "-")))
    file.rename(from, to)
  }
})
knit_hooks$set(chunk = function(x, options){
  if (is.null(options$fig.names)){
     knitr:::.chunk.hook.tex(x, options)
  } else {
    chunk_name = opts_current$get('label')
    x = gsub(sprintf('%s[0-9]', chunk_name), 
      sprintf("%s-%s", chunk_name, options$fig.names), x)
    knitr:::.chunk.hook.tex(x, options)
  }
});
@


<<iris, fig.names = letters[1:4]>>=
invisible(lapply(iris[,-5], hist, col = 'gray', border = 'white'))
@

\end{document}
+3

All Articles