Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include multiple graphics with R-markdown

I have an R vector of filepaths for pdf figures I would like to put into my knitr document and knit to html. I see that I can get a single pdf to be included with

knitr::include_graphics(filepaths[1])

My filepaths vector is long and changes size between document compilations. Is there a method of including them all in one go. I had imagined this would work.

for(i in filepaths){knitr::include_graphics(i)}

Had also tried:

for(i in filepaths){ print("![](", filepaths[i], ")" ) }
like image 617
Seth Avatar asked Oct 20 '25 04:10

Seth


2 Answers

knitr::include_graphics() is vectorized, so the answer is simply:

knitr::include_graphics(filepaths)

Your first solution does not work because knitr::include_graphics() needs to be the top-level expression. Your second solution does not work because you should use cat() instead of print(), and the chunk option results='asis'.

There are several advantages of using include_graphics() over cat() + results='asis'.

like image 91
Yihui Xie Avatar answered Oct 21 '25 17:10

Yihui Xie


Try using cat instead of include_graphics. For example:

for(i in 1:length(filepaths) {
    cat("![](", filepaths[i], ")")
}

This is general Markdown syntax: ![NAME](PATH).
With this solution you will need to use results = "asis" in chunk header.

like image 40
pogibas Avatar answered Oct 21 '25 18:10

pogibas