Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parametrized Rmarkdown: Use value of param A in definition of param B

Conceptually I want to do something like this:

---
title: Fun With Params
output: html_document
params:
   x: 1
   y: !r params$x + 1
--- 

```{r}
params
```

That is I want to use the value of one parameter in the definition of another one.

This does not work. It renders though with an Error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Error in eval(expression) : object 'params' not found
Calls: <Anonymous> -> eval -> eval

Warning message:
In yaml::yaml.load(yaml, handlers = knit_params_handlers(evaluate = evaluate),  :
  an error occurred when handling type 'r'; using default handler

And the document looks like this:
Screenshot of the rendered RMarkdown where params$y renders to the (unevaluated) text

Basically, this tells me that in the moment the YAML header is parsed params does not yet exist and parms$x cannot be evaluated, hence it returns simply the string.

I could assign a default value (NULL say) and push the logic to my first chunk. This, however, has the annoying drawback that in RStudio I should not forget to run this very chunk to get the proper value of params$y. This is of course not an issue when rendering the full document, but annoying if I want (for whatever reason) to run some chunks (not necessarily in order) interactively.

Thus, is there a way how I could use another param in the definition of another one?

>Solution :

I don’t think this is wholly satisfactory, but one approach would be to use dplyr::lst() which allows the sequential building of objects. This would result in a nested parameter object however.

---
title: Fun With Params
output: html_document
params: 
  myparams: !r dplyr::lst(x = 1, y = x + 1)
--- 

```{r}
params
```

enter image description here

Alternatively, you could put some placeholders in your YAML header and replace these with a render() call:

---
title: Fun With Params
output: html_document
params:
  x: NA
  y: NA
--- 

```{r}
params
```

And use:

rmarkdown::render("funwithparams.rmd", params = dplyr::lst(x = 1, y = x + 1))

Giving:

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading