Use R code or Windows user variable (“%userprofile%”) in YAML?

吃可爱长大的小学妹 提交于 2019-12-11 03:48:29

问题


In my yaml call I have

---
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
---

But YAML complains about %userprofile%. Is it possible to include such a variable?

I have tried e.g.

reference_docx: "`r file.path(path.expand('~'), 'skabelon.docx')`"

But that still results in this YAML error.

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

I guess this meens that the r expression is not processed before the yaml? I have checked that the file is there... Or is it becayse pandoc is using another 'userprofile' ? how can I check this?

I can however use such a call in the Title variable, as per the updated title above. I guess this must be a specific knitr issue.


回答1:


The problem is that the parameters in the output field is only understood by rmarkdown. Pandoc does not understand them, so you need to make sure rmarkdown can evaluate the expression. Since rmarkdown uses the yaml package to read the YAML metadata, and yaml's syntax for R expressions is !expr, you can put the R expression after !expr, e.g.

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



回答2:


You can include such a variable, but you should quote the scalar in which put it (either single quotes or double quotes). Within a quoted scalar the % doesn't have any special meaning only the single quote has (in single quoted strings, or the backslash (\) in double quoted strings.

Any further interpretation of that scalar as Windows variable is outside of the scope of YAML and needs to be done by your program.

The scalar:

"`r file.path(path.expand('~'), 'skabelon.docx')`"

is correct YAML and shout not throw an error (but of course is nothing else for YAML than a buch of characters starting and ending with a backquote, no interpretation should be done on that by the parser).



来源:https://stackoverflow.com/questions/41148853/is-there-a-way-to-use-inline-r-in-yaml-refernce-docx-when-knitting-to-word

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!