在knitr中使用YAML头参数

kri*_*ang 7 r beamer pandoc knitr r-markdown

我正在使用一组幻灯片rmarkdown和输出它的LaTeX选项beamer.

我在幻灯片中使用了两个模板 - 一个专门用于LaTeX选项,另一个是我修改过的pandoc模板,用于说明幻灯片的一些其他功能.

我已在YAML标头中定义了一个选项,该选项to_print是一个布尔值TRUE/FALSE,我将其传递给pandoc模板,该模板告诉它添加包并清理幻灯片以进行打印.

我还想使用此变量来定义文件的名称.基本的想法是,我想.rmd为我的幻灯片创建一个文件,然后只需更改这一个选项即可表示它是供学生打印的,或者是我的演示文稿.

我已经发现我可以render使用knitYAML头中的参数传递函数,但是我必须相应地在output_file to_print = TRUE中的ifelse()语句中指定和设置条件.

目前我有:

---
title: "Introduction to R"
subtitle: "Reading and saving data in R"
date: '`r format(Sys.Date())`'
output:
  beamer_presentation:
    fonttheme: professionalfonts
    highlight: tango
    includes:
      in_header: "../../templatefiles/beamer_header.tex"
    template: "../../templatefiles/beamer_template.tex"
    incremental: no
    keep_tex: yes
    slide_level: 3
    theme: Warsaw
    toc: yes
fontsize: 10pt
fontenc: T1
to_print: TRUE
knit: (function(inputFile, encoding) { rmarkdown::render(inputFile, encoding = encoding, 
       output_file = file.path(ifelse(TRUE,
                                      gsub("\\..*","_handout.pdf", inputFile), 
                                      gsub("\\..*", ".pdf", inputFile)))) })
---
Run Code Online (Sandbox Code Playgroud)

我想指定一个参数,然后用于表示这是否是要打印的讲义:

伪代码:

to_print: TRUE
knit: (function(inputFile, encoding) {rmarkdown::render(inputFile, encoding = encoding, 
       output_file = file.path(ifelse(YAML_PARAM$to_print,
                                      gsub("\\..*","_handout.pdf", inputFile), 
                                      gsub("\\..*", ".pdf", inputFile)))) })
Run Code Online (Sandbox Code Playgroud)

这是可能的,还是等同于让我有一个.rmd带有布尔值的文件来切换演示文稿与打印的东西?

RLe*_*sur 3

您可以使用该rmarkdown::yaml_front_matter()功能:

---
title: "Introduction to R"
subtitle: "Reading and saving data in R"
date: '`r format(Sys.Date())`'
output:
  beamer_presentation:
    fonttheme: professionalfonts
    highlight: tango
    includes:
      in_header: "../../templatefiles/beamer_header.tex"
    template: "../../templatefiles/beamer_template.tex"
    incremental: no
    keep_tex: yes
    slide_level: 3
    theme: Warsaw
    toc: yes
fontsize: 10pt
fontenc: T1
to_print: TRUE
knit: (function(inputFile, encoding) { rmarkdown::render(inputFile, encoding = encoding, 
       output_file = file.path(ifelse(rmarkdown::yaml_front_matter(inputFile)$to_print,
                                      gsub("\\..*","_handout.pdf", inputFile), 
                                      gsub("\\..*", ".pdf", inputFile)))) })
---
Run Code Online (Sandbox Code Playgroud)