Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

include images programmatically in .md document from within R chunk using knitr

Tags:

r

knitr

I want to programmatically include a lot of images in my .Rmd markdown document. Something like

```{r echo=FALSE}
cat("![](myfile_1.png)")
```

will not work, as the resulting .md output is

```
## ![](myfile_1.png)
```

I would need to get rid of the code tags ``` and the leading ##. Is there an option to directly inject markdown code from within the R chunk?

BTY: The same issue applies to HTML as well. Here also a HTML code injection from within an R chunk would be really helpful.

like image 951
Mark Heckmann Avatar asked Jun 19 '12 08:06

Mark Heckmann


People also ask

How do I add an image in R Markdown?

To add an image in markdown you must stop text editing, and you do this with the command [Alt text] precedeed by a ! Then you have to add the path to the image in brackets. The path to the image is the path from your directory to the image.

How do I embed a code into chunks in R?

You can insert an R code chunk either using the RStudio toolbar (the Insert button) or the keyboard shortcut Ctrl + Alt + I ( Cmd + Option + I on macOS).

How can you compile the R Markdown document using knitr package?

The usual way to compile an R Markdown document is to click the Knit button as shown in Figure 2.1, and the corresponding keyboard shortcut is Ctrl + Shift + K ( Cmd + Shift + K on macOS). Under the hood, RStudio calls the function rmarkdown::render() to render the document in a new R session.


1 Answers

Using results ='asis' means that you don't have to mess with the hooks, comments etc as the results are not considered code, but markdown (or whatever the output format happens to be)

```{r myfile-1-plot, echo = F, results = 'asis'}
cat('\n![This is myfile_1.png](myfile1.png)\n')
```

Will result in

![This is myfile_1.png](myfile1.png)

Note that I wrapped the output text with new line markers to ensure that it is on a separate line.

like image 107
mnel Avatar answered Nov 14 '22 21:11

mnel