Rmarkdown knitr::include_graphics无法在循环(loop)中使用

这个问题困扰一天两夜,记录一下
解决办法参考s1

问题:

Shiny 接收多个文件,每个文件生成一张图片,结束。最后将地址通过 params 传给 Rmarkdown(Rmd),生成报告。这里面需要在Rmd中进行遍历,但是在for loop中遍历 使用knitr::include_graphics() 无法在Rmd展示图片。Demo Code:

Shiny

library(shiny)
shinyApp(
  ui = fluidPage(
    textInput("s1", "Description 1", "image1.png"),
    textInput("s2", "Description 2", "image2.png"),
    downloadButton("report", "Generate report")
  ),
  server = function(input, output) {
    output$report <- downloadHandler(
      filename = "report.html",
      content = function(file) {
        tempReport <- file.path(tempdir(), "report.Rmd")
        file.copy("volcano2.Rmd", tempReport, overwrite = TRUE)
        params <- list(tag = c(input$s1, input$2"))
        rmarkdown::render(tempReport, output_file = file,
                          params = params,
                          envir = new.env(parent = globalenv())
        )
      }
    )
  }
)

为了突出主要问题,这里直接把已经存在tempdir()的图片名作为 params。

volcano2.Rmd

---
title: 
xxxx
author:
`r knitr::opts_chunk$set(echo = FALSE, out.width="30%")``r knitr::include_graphics(paste("G:\\Project\\workspace","www\\xxx.jpg",sep="\\"))`
date:
`r format(Sys.Date(),'%Y-%m-%d')`
runtime: "static" params: tag: NA output: html_document: toc: no toc_float: yes keep_md: true theme: flatly number_sections: false --- ``` {r} knitr::opts_chunk$set(echo = FALSE, message = TRUE, warning = TRUE) ``` # Rmd的R 代码块于md语法的代码一样,为了避免歧义这样写 # xxxxx   1234 ### {.tabset .tabset-fade .tabset-pills} ```{r, results='asis', out.width='60%', echo=FALSE} n <- params$tag for (i in n){ cat("#### " ,i, "\n\n") a <- paste(tempdir(), i, sep = "\\") cat(knitr::include_graphics(a)) # knitr::include_graphics(a) cat('\n\n') } ``` ### {-}

cat(knitr::include_graphics(a)) 不出图的原因参见yihui : include_graphics() has to be used in top-level R expressions. 即无法在循环内使用,因此解决办法有:

1. Rmd插入图片,但是无法改样式

```{r, results='asis', out.width='60%', echo=FALSE}
n <- params$tag
for (i in n){
  cat("#### " ,i, "\n\n")
  a <- paste(tempdir(), i, sep = "\\")
 aaa #见下面
  cat('\n\n')
} ``` 

2.HTML插入图片,可以改样式,推荐!!!

```{r, results='asis', out.width='60%', echo=FALSE}
n <- params$tag
for (i in n){
  cat("#### " ,i, "\n\n")
  a <- paste(tempdir(), i, sep = "\\")
  cat("")
  cat('\n\n')
} ```

aaa : cat("[图片上传失败...(image-3b0c65-1598935814989)]")

你可能感兴趣的:(Rmarkdown knitr::include_graphics无法在循环(loop)中使用)