且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将R Markdown转换为pdf时的受防护代码块

更新时间:2022-11-09 18:55:21

使用```,您将引入普通的markdown代码块,但不会引入knitr代码块.但是您期望的输出(围栏,突出显示,阴影)是knitr样式添加到其代码块中的样式.

With ``` you introduce a plain markdown code block but not a knitr code chunk. But the output you expect (fencing, highlighting, shading) is the style knitr adds to its code blocks.

因此,请使用```{r}将代码包装在knitr块中(如果不想评估代码,请使用eval = FALSE).这也可以用于非R代码块:只要不对代码求值,语言就没有关系.

Therefore, use ```{r} to wrap code in knitr chunks (use eval = FALSE if you don't want the code to be evaluated). This can also be used for non-R code blocks: As long as the code is not evaluated, the language doesn't matter.

但是,对于非R代码,这将导致错误或缺少语法突出显示.要获得正确的语法高亮显示,请使用选项 engine(如果该语言属于支持的语言引擎.

However, for non-R code this will lead to wrong or missing syntax highlighting. To get the correct syntax highlighting, use the option engine if the language is among the supported language engines.

下面的示例显示了痛苦减价块,一个经过评估和未经评估的R代码块,一个(未经评估的)Python块而没有突出显示,最后是两个(未经评估的)Python块具有正确的突出显示.

The example below shows a pain markdown block, an evaluated and and unevaluated R code chunk, a (unevaluated) Python chunk without highlighting and finally two (unevaluated) Python chunks with correct highlighting.

---
output:
  pdf_document
---

```
Plain markdown code block.
```


```{r}
print("This is a knitr code chunk.")
```

```{r, eval = FALSE}
print("This is a knitr code chunk that isn't evaluated.")
```


Chunk with Python code (borrowed from http://***.com/q/231767/2706569), *wrong* (no) highlighting:
```{r, eval = FALSE}
if self._leftchild and distance - max_dist < self._median:
      yield self._leftchild
```

Chunk with Python code, *correct* highlighting:
```{r, eval = FALSE, engine = "python"}
if self._leftchild and distance - max_dist < self._median:
      yield self._leftchild
```

Chunk with Python code, *correct* highlighting (alternative notation):
```{python, eval = FALSE}
if self._leftchild and distance - max_dist < self._median:
      yield self._leftchild
```