简体   繁体   English

在 RMarkdown 文档中包含 YAML 文件

[英]Include YAML file in RMarkdown document

I have an RMarkdown document that includes an example YAML file, currently in the form:我有一个 RMarkdown 文档,其中包含一个示例 YAML 文件,当前格式为:

```{yaml}
name: r40_tidyverse
channels:
  - conda-forge
  - nodefaults
dependencies:
  - r-base=4.0
  - r-tidyverse
```

This renders (knits) into HTML with nice YAML syntax highlighting.这会渲染(编织)到 HTML 中,并带有漂亮的 YAML 语法突出显示。

Knitted Result针织结果渲染的 YAML 代码

Instead of the above, I would like to include it as an external YAML file, say at envs/r40_tidyverse.yaml .除了上述内容,我想将其作为外部 YAML 文件包含在envs/r40_tidyverse.yaml中。 I have tried using我试过使用

```{yaml child="envs/r40_tidyverse.yaml"}
```

While this correctly loads the file, the resulting HTML is merely a <p></p> element with the contents of the file located within it.虽然这会正确加载文件,但生成的 HTML 只是一个<p></p>元素,文件内容位于其中。

Knitted Result针织结果未渲染的 YAML 文件

This is not desirable.这是不可取的。

How can one load an external YAML file into an RMarkdown document and achieve syntax highlighting similar to when including a YAML code chunk directly?如何将外部 YAML 文件加载到 RMarkdown 文档中并实现类似于直接包含 YAML 代码块时的语法突出显示?

I think the easiest way is that you read the external file in an inline R expression, eg,我认为最简单的方法是您在内联 R 表达式中读取外部文件,例如,

```yaml
`r xfun::file_string('envs/r40_tidyverse.yaml')`
```

Note that you should not use ```{yaml} (ie, do not add {} to yaml ), because that would change its meaning to knitr :请注意,您不应使用```{yaml} (即,不要将{}添加到yaml ),因为这会将其含义更改为knitr

  • With curly braces, it means a code chunk, and a knitr language engine needs to evaluate the code chunk (but there is not a yaml engine yet, and your first example worked just by chance).使用花括号,它表示代码块,并且knitr语言引擎需要评估代码块(但还没有yaml引擎,您的第一个示例只是偶然工作)。
  • Without curly braces, it means a normal code block, which will not be processed by knitr .没有大括号,表示正常的代码块,不会被knitr处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM