在YAML中使用R代码或Windows用户变量("%userprofile%")?

And*_*eas 6 yaml r user-profile knitr r-markdown

在我的yaml电话中,我有

---
title: "`r paste0('Test. Done ', format(Sys.Date(), '%B-%Y'))`"
output:
  word_document:
    fig_caption: yes
    fig_height: 4
    fig_width: 7
    reference_docx: %userprofile%\Documents\template.docx
---
Run Code Online (Sandbox Code Playgroud)

但YAML抱怨%userprofile%.是否可以包含这样的变量?

我试过例如

reference_docx: "`r file.path(path.expand('~'), 'skabelon.docx')`"
Run Code Online (Sandbox Code Playgroud)

但这仍然会导致YAML错误.

pandoc.exe: `r file.path(path.expand('~'), 'skabelon.docx')`: openBinaryFile: does not exist (No such file or directory)
Run Code Online (Sandbox Code Playgroud)

我想这可能是在yaml之前没有处理r表达式吗?我已经检查过该文件是否存在...或者是因为pandoc正在使用另一个'userprofile'?我怎么检查这个?

然而Title,根据上面更新的标题,我可以在变量中使用这样的调用.我想这一定是特定的针织问题.

Yih*_*Xie 7

问题是该output字段中的参数仅由rmarkdown理解.Pandoc不理解它们,因此您需要确保rmarkdown可以评估表达式.由于rmarkdown使用yaml包来读取YAML元数据,并且yaml的R表达式的语法是!expr,你可以将R表达式放在后面!expr,例如

output:
  word_document:
    fig_caption: yes
    fig_height: 4
    fig_width: 7
    reference_docx: !expr file.path(Sys.getenv('USERPROFILE'), 'Documents', 'template.docx')
Run Code Online (Sandbox Code Playgroud)

  • 这有效@Yihui。但这是否意味着“!expr”取代了“`r”?我可以在 yaml 包中找到这一点 - 但在其他地方找不到。在我的示例中,“'r”适用于日期字段,但 !expr 不适用。另一方面 !expr 适用于 reference_docx 但 "'r" 不适用?有什么不同? (2认同)
  • 好问题。`r` 语法只有 knitr 才能理解。在您的情况下,您希望 rmarkdown 理解它是一个 R 表达式。由于 rmarkdown 使用 yaml 来解析 YAML 元数据,而 yaml 只能理解 `!expr`。 (2认同)