R Markdown how to make parameter optional

Viewed 330

Is there a way to make a parameter optional in R Markdown when using knitr? Below is a stand-alone example, my simple attempt to omit a parameter, and the error.

Example RMD file:

---
title: "`r params$name`"
date: \`r format(Sys.Date(), "%B %d, %Y")`\
output:
  html_document:
    toc: true
params:
    name: NA
    A: NA
    B: NA
    C: NA
--- 
# Header-1

`r params$A` 
`r params$B`
```{r, echo=FALSE, out.width="50%"}
knitr::include_graphics(params$C)
```

Example run script:

render(input = "mytemplate.Rmd", 
       output_file = "fileout.html", 
       params = list(
         name = 'Bob', 
         A = 'turkey', 
         B = 'otter'
         )
       )

Resulting error when omitting "C":

Error in knitr::include_graphics(params$C) : 
  Cannot find the file(s): NA
1 Answers

Not passing C value in params works fine for me. It prints the default value (NA) in the HTML output. I get an error because name is not declared. Using the below works -

---
title: "`r params$name`"
date: \`r format(Sys.Date(), "%B %d, %Y")`\
output:
  html_document:
    toc: true
params:
    A: NA
    B: NA
    C: NA
    name: NA
--- 
# Header-1

`r params$A` 
`r params$B`
`r params$C`

and calling it with

rmarkdown::render(input = "mytemplate.Rmd", 
       output_file = "fileout.html", 
       params = list(
         name = 'Bob', 
         A = 'turkey', 
         B = 'otter'
       )
)

For the updated question you can add an if condition :

`r params$A` 
`r params$B`
```{r, echo=FALSE, out.width="50%"}
if(params$C != 'NA') knitr::include_graphics(params$C)
Related