我使用Window 10系统, 写了rmd文件放在E盘, 具体为E:\doc\work.rmd
, 其中用knitr::include_graphics
插入1张放在C:\Users\lenovo\Desktop\test\demo.png
的图片, demo如下:
---
title: "Title"
author: "Author"
date: '2024'
output:
word_document: default
html_document:
df_print: paged
keep_md: no
pdf_document:
latex_engine: xelatex
keep_tex: no
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, warning = FALSE)
```
## Including Plots
You can also embed plots, for example:
```{r demo1, echo=F, out.width="100%", eval=T}
knitr::include_graphics('C:/Users/lenovo/Desktop/test/demo.png')
```
Starting with **R 4.0**, it is recommended to use the new raw string literal syntax (see `?Quotes`). The syntax looks like `r"(...)"`, where `...` can contain any character sequence, including `\`. For example, A Windows path written as a raw string constant:
```{r eval=FALSE}
r"(c:\Program files\R)"
```
```{r demo2, echo=F, out.width="100%", eval=T}
knitr::include_graphics(r"(C:\Users\lenovo\Desktop\test\demo.png)")
```
结果显示, 当运行html_document
时, 代码块demo1
和demo2
都可以成功生成html(代码块demo1
和demo2
运行生成word也是成功的); 但当运行pdf_document
时, demo2
代码块会导致生成pdf报错!
在Window系统中使用Windows raw path可以提高效率, 不用手动反斜杠. 不知道问题出在哪里? 用keep_tex: yes
发现r"(...)"
并未对路径进行改变, 但逻辑上knitr::include_graphics(r"(...)")
不是应该对HTML, Word和PDF三种都可行吗? 如果要用raw路径生成PDF有没有其他解决办法?
当然了, 通过阅读Yihui Xie的官方书籍guide和cookbook, 明白无误的是HTML, Word和PDF三种文档的确是不同的, 所谓“泥鳅黄鳝不能一样长”, 但是联想到插入图片对这三种都是基本操作, 所以有上述提问...