Insert images using knitr::include_graphics in a for loop

后端 未结 2 2032
梦如初夏
梦如初夏 2020-12-03 11:44
```{r}
knitr::include_graphics(path = \"~/Desktop/R/Files/apple.jpg/\")
```

The above code chunk works fine. However, when I create a for

相关标签:
2条回答
  • 2020-12-03 12:42

    This is a known issue knitr include_graphics doesn't work in loop #1260.

    A workaround is to generate paths to images within a for loop and cat them. To show final result result = "asis" is required.

    ```{r, results = "asis"}
    fruits <- c("apple", "banana", "grape")
    for(i in fruits) {
        cat(paste0("![](", "~/Desktop/R/Files/", i, ".jpg)"), "\n")
    }
    ```
    

    Here each iteration generates markdown path to graphics (eg, "![](~/Desktop/R/Files/apple.jpg)")

    0 讨论(0)
  • 2020-12-03 12:42

    include_graphics() has to be used in top-level R expressions as Yihui stated here

    My workaround is this:

    ```{r out.width = "90%", echo=FALSE, fig.align='center'}
    files <- list.files(path = paste0('../', myImgPath), 
                        pattern = "^IMG(.*).jpg$",
                        full.names = TRUE)
    
    knitr::include_graphics(files)
    
    ```
    
    0 讨论(0)
提交回复
热议问题