Created
June 23, 2017 23:45
-
-
Save AlexAxthelm/9f7eefba060732f29dbe094211ef8985 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
title: "Escaping R Code in RMarkdown Paramaters" | |
author: "Alex Axthelm" | |
date: "6/23/2017" | |
output: html_document | |
params: | |
unescaped_add: 1 + 1 | |
unescaped_fun: rnorm(10) | |
escaped_add: !r 1 + 1 | |
escaped_fun: !r rnorm(10) | |
--- | |
```{r setup, include=FALSE} | |
knitr::opts_chunk$set(echo = TRUE) | |
``` | |
# Basic Magic Demo | |
Let's explore the magic of escaping paramaters in R markdown. | |
First, Let's look at what an unescaped paramater looks like: | |
```{r} | |
params$unescaped_add | |
params$unescaped_fun | |
``` | |
Notice that these are evaluated as literal strings. R doesn't do any evaluation of the code inside | |
## BUT! | |
Let's see what happens when we escape our R code using `!r`: | |
```{r} | |
params$escaped_add | |
params$escaped_fun | |
``` | |
Remember that these `params` need to be defined in YAML header, or when calling `rmarkdown::render` | |
## Note: It's not actually a function call | |
Let's revisit `escaped_fun`. A person might be inclined to believe that R is evaluating that when it reads the YAML. That person is exactly correct: | |
```{r} | |
# It's the same as above | |
params$escaped_fun | |
#still the same values, because the values are stored not evaluated: | |
set.seed(42) | |
params$escaped_fun | |
``` | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment