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

依然范特西╮ 提交于 2020-01-01 09:50:34

问题


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.


回答1:


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.




回答2:


Assuming that you use knitr, you could use the comment option:

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

Edit

You will have to change the hooks:

```{r echo=FALSE, comment=""}
knit_hooks$set(output = function(x,
        options) x)
cat("![](myfile_1.png)")
```

When you want to render markdown again, make sure to reset your hooks again, one way would be to use render_markdown().

```{r b, echo=FALSE, comment=""}
render_markdown()
a <- 1
```



回答3:


To use in a loop, if you need to paste a bunch of pictures from a data frame:

for(h in 1:nrow(file_names)){
   image_file<-paste('\n![](', file_names[h],')\n',sep="") 
   cat('\n')
   cat(image_file)
   cat('\n')
}


来源:https://stackoverflow.com/questions/11096870/include-images-programmatically-in-md-document-from-within-r-chunk-using-knitr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!