Replace variables with their corresponding values in source code chunk
knitr, r, r-markdown
Solution
You could modify the source hook. A solution tailored to your need follows immediately. For a more general approach, that replaces all elements in `params`, scroll down.
---
output:
pdf_document: default
html_document: default
params:
file: samples.txt
---
{r, include=FALSE} library(knitr) library(stringr) default_source_hook <- knit_hooks$get('source')
knit_hooks$set(source = function(x, options) { x <- str_replace_all(x, pattern = 'params\\$file', paste0("'",params$file,"'")) default_source_hook(x, options) })
{r print, echo=T, comment="", eval = T} print(params$file)
`
First we save the default hook that would be used depending on the output file type (`render_html` or `render_latex` etc.). Then we change the source hook: we replace all occurrences of `params$file` with its value and then throw the source code back into the default hook we saved before.
In this case this results in:
This magic works, because we only modify the source code that will be printed, not the one being evaluated!
Update: A more general Approach
I played a bit with your example and created a more general hook. It should replace all elements of the form `params$...` in your code chunks. It even checks for the type of value and adds quotes if it is a character value.
Check the following MRE:
---
output:
pdf_document: default
html_document: default
params:
file: samples.csv
age: 28
awesome: true
34: badname
_x: badname
---
{r, include=FALSE} library(knitr) library(gsubfn)
default_source_hook <- knit_hooks$get('source')
knit_hooks$set(source = function(x, options) { x <- gsubfn(x = x, pattern = "params\\$`?([\\w_]+)`?", function(y) { y <- get(y, params) ifelse(is.character(y), paste0("'", y, "'"), y) }) default_source_hook(x, options) })
{r print, echo=T, comment="", eval = T} file <- params$file age <- params$age awsm <- params$awesome # dont name your variables like that! works though... badexmpls <- c(params$`34`, params$`_x`)
`
We make use of `gsubfn()`. This function allows us to use a function for the replacement attribute (not possible in common `gsub`). This function takes on the elements found, but, thanks to regex only the part after the `$`. So in this chunk, `y` equals `file`, `age` and `awesome`.
Problem
I'd like to show parameter values and not `params$...` in R Markdown output. For example, the first code chunk below displays `params$file` in the output, but I'd like to replace that with `samples.txt`. I tried adding a second chunk with `message`, but that outputs a white code chunk and I'd like a gray background like all other R code blocks. ```` --- output: html_document params: file: samples.txt --- ```{r read, message=FALSE, collapse=TRUE, comment=""} x <- read_tsv(params$file) x ``` This just needs a gray background ```{r print, echo=2, collapse=TRUE, comment=""} message('x <- read_tsv("', params$file, '")') x ``` ````