Insert images using knitr::include_graphics in a for loop

浪子不回头ぞ 提交于 2019-12-19 09:48:25

问题


```{r}
knitr::include_graphics(path = "~/Desktop/R/Files/apple.jpg/")
```

The above code chunk works fine. However, when I create a for loop, knitr::include_graphics does not appear to be working.

```{r}
fruits <- c("apple", "banana", "grape")
for(i in fruits){
  knitr::include_graphics(path = paste("~/Desktop/R/Files/", i, ".jpg", sep = ""))
}
```

回答1:


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)")




回答2:


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)

```


来源:https://stackoverflow.com/questions/51268623/insert-images-using-knitrinclude-graphics-in-a-for-loop

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