在for循环中使用classr::include_graphics插入图像

hl0ma9xz  于 2023-11-14  发布在  其他
关注(0)|答案(2)|浏览(104)
```{r}
knitr::include_graphics(path = "~/Desktop/R/Files/apple.jpg/")
字符串
上面的代码块工作正常。但是,当我创建一个`for`循环时,`knitr::include_graphics`似乎不工作。
fruits <- c("apple", "banana", "grape")
for(i in fruits){
  knitr::include_graphics(path = paste("~/Desktop/R/Files/", i, ".jpg", sep = ""))
}
jvidinwx

jvidinwx1#

这是一个已知问题knitr include_graphics doesn't work in loop #1260
解决方法是在for循环中生成指向图像的路径,并对它们进行cat。要显示最终结果,需要result = "asis"

```{r, results = "asis"}
fruits <- c("apple", "banana", "grape")
for(i in fruits) {
    cat(paste0("![](", "~/Desktop/R/Files/", i, ".jpg)"), "\n")
}
字符串
这里,每次迭代都会生成到图形的减价路径(例如,`"![](~/Desktop/R/Files/apple.jpg)"`)
dbf7pr2w

dbf7pr2w2#

include_graphics()必须在顶级R表达式中使用,正如Yihui所说的here
我的解决方法是:

```{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, error = FALSE)
字符串

相关问题