【问题标题】:Insert images using knitr::include_graphics in a for loop在 for 循环中使用 knitr::include_graphics 插入图像
【发布时间】:2018-07-10 15:04:57
【问题描述】:
```{r}
knitr::include_graphics(path = "~/Desktop/R/Files/apple.jpg/")
```

上面的代码块工作正常。但是,当我创建 for 循环时,knitr::include_graphics 似乎不起作用。

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

【问题讨论】:

    标签: r knitr


    【解决方案1】:

    这是一个已知问题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)"

    【讨论】:

    • 谢谢@PoGibas。使用print(paste0("![](", "~/Desktop/R/Files/", i, ".jpg)")) 有效,但我在图像周围看到[1]""(即我似乎打印了一组额外的引号)。
    【解决方案2】:

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

    【讨论】:

    • 此解决方案也适用于 files &lt;- dir("path/to/files/", pattern = "pattern.*jpg$", full.names = TRUE) 而不是 list.files
    • 关于为什么这样有效的说明。 list.files 输出一个类字符向量,这是 include_graphics 所期望的。所以文件可以是文件路径的任何字符向量,或者是转换为as.character(list_of_paths)list例如 {r} fruits &lt;- c("apple", "banana", "grape"); files &lt;- lapply(X = fruits, FUN = function(fr){ file.path("~/Desktop/R/Files/",paste0(fr, ".jpg") ) } ) ; knitr::include_graphics( as.character(files) )
    猜你喜欢
    • 2021-07-25
    • 1970-01-01
    • 2016-12-03
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 2014-10-14
    • 1970-01-01
    • 2017-04-17
    相关资源
    最近更新 更多