Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 237
Andreas Avatar asked Nov 25 '16 09:11

Andreas


1 Answers

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')
like image 109
Yihui Xie Avatar answered Oct 22 '22 01:10

Yihui Xie