首页 > 解决方案 > 在 pdf 输出中包含示例/练习块中的代码块

问题描述

Bookdown 通过为定理、示例和练习(以及更多)添加环境来扩展 R markdown。我想在示例环境中放置一个代码块:

```{example, label="ex1"}
Here is an example:

```{r eval=FALSE}
x <- 1+1
x+2
```

```

所需的输出如下:


示例 1.这是一个示例:

x <- 1+1
x+2

上面的代码不起作用,因为代码块已经在 ``` 环境中。

我找到了以下解决方法,当我将文档编织到 html 页面时效果很好:

```{example, label="ex1"}
Here is an example:

<pre><code>
x <- 1+1
x+2
</code></pre>

```

不幸的是,当我将文档编织成 pdf 文件时,这不起作用 - 相反,我只是得到一个空格。有没有一种适用于 html 和 pdf 输出的方法?


更新:另一个不起作用的解决方案如下(基于):

  ```{example, label="ex1"}
  Here is an example:

  ````
  `r ''````x <- 1+1
  x+2
  ```
  ````
  ```

在这种情况下,问题在于 1+1 和 x+2 之间的换行符消失了。

标签: rr-markdownbookdown

解决方案


我不知道为什么,但以下解决方案的作品:

```{example, label="ex1"}
Here is an example:

```{r eval=FALSE}
x <- 1+1
x+2

```

这是我最初的建议,删除了第二个```。

缺点是示例中在 ```{r eval=FALSE} 部分之后的所有文本现在都变成了逐字记录。


推荐阅读