rr-markdownknitr

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:

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