Rmarkdown knitr::include_graphics無法在循環(huán)(loop)中使用

這個(gè)問題困擾一天兩夜,記錄一下
解決辦法參考s1

問題:

Shiny 接收多個(gè)文件,每個(gè)文件生成一張圖片,結(jié)束。最后將地址通過 params 傳給 Rmarkdown(Rmd),生成報(bào)告。這里面需要在Rmd中進(jìn)行遍歷,但是在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())
        )
      }
    )
  }
)

為了突出主要問題,這里直接把已經(jīng)存在tempdir()的圖片名作為 params。

volcano2.Rmd

---
title: <center>xxxx</center>
author: <center>`r knitr::opts_chunk$set(echo = FALSE, out.width="30%")``r knitr::include_graphics(paste("G:\\Project\\workspace","www\\xxx.jpg",sep="\\"))`</center>
date: <center>`r format(Sys.Date(),'%Y-%m-%d')`</center>
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
&emsp;&emsp;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. 即無法在循環(huán)內(nèi)使用,因此解決辦法有:

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("<img src=",a," width='60%' height='60%' align = center />")
  cat('\n\n')
} ```

aaa : cat("[圖片上傳失敗...(image-3b0c65-1598935814989)]")

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。