Using R markdown and knitr: Possible to get R objects interpreted in YAML

ε祈祈猫儿з 提交于 2019-12-06 02:41:38

It's not exactly YAML-related, and limited to latex, but maybe this helps. Sorry, the thread is in German, but maybe the code is clear enought.

You can pick items for the abstract as you create your report; the items are written out to a temporary file similar to method use in bibtex and biblatex, and merged to the start and end (for appendix) in a second step.

As a package, you can download it from here .

Requirements

Install R, knitr, and yaml:

sudo su -
apt-get install pandoc
apt-get install r
r
url <- "http://cran.us.r-project.org"
install.packages('knitr', repos=url)
install.packages('yaml', repos=url)

Create Variables

Separate the variables into a new file (e.g., v.yaml):

title: 'How do I interpret R objects in YAML that are created in the document?'
author: Jeff Hollister
output:
  pdf_document:
    fig_caption: yes
    keep_tex: yes
    number_sections: yes
  html_document: null
  word_document: null
fontsize: 11pt
documentclass: article
abstract:  This is a test.  Is this `r mean(x)` working?

Create Script

Create a script to load knitr, yaml, and the variables (e.g., knitr.sh), when given a file in Markdown format:

#!/bin/bash

R -e \
"library(knitr); library(yaml); v <- yaml.load_file('v.yaml'); knit('$1')"

Reference Variables

Use R statements (inline or otherwise) to reference the source document variables (document.md):

# `r v$title`
Author: `r v$author`

Run Script

Generate a knitr-processed Markdown file by running the script:

./knitr.sh document.md

View Output

The file document.txt (renaming is a problem left for the reader) should contain the following Markdown:

# How do I interpret R objects in YAML that are created in the document?
Jeff Hollister

Addendum

It is fairly trivial with shell script magick to insert the variables at the top of the generated file, should they be needed for processing by pandoc. If using YAML variables for pandoc's templates, I'd recommend skipping that route and using R variables instead.

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