Home > Enterprise >  Run an R Markdown based on interactive parameter choice
Run an R Markdown based on interactive parameter choice

Time:02-07

I am trying to do the following on R Markdown. Basically, I would like the user to be able to select between two values of a parameter called "Machine" and based on the value selected run some chunks and not others. I know that the "eval" option might be useful here but I have no clue on how to use it in order to reach my goal. My code for the moment is this (in R Markdown):

    ---
title: "SUM and SAM"
output: html_document
params:
  machine:
  label: "Machine"
  value: SUM
  input: select
  choices: [SUM, SAM]
  printcode:
    label: "Display Code:"
    value: TRUE
  date: !r Sys.Date()
  data:
    label: "Input dataset:"
    value: None
    input: file
  years_of_study:
    input: slider
    min: 2018
    max: 2020
    step: 1
    round: 1
    sep: ''
    value: [2018, 2019]

---


```{r setup, include=FALSE}

############# IMPORTANT ################################### 
#Remember to Knit with Parameters here using the "Knit button"--> "Knit with Parameters".
#################################################### 

#If you only want the parameters to be shown, run the following.
#knit_with_parameters('~/Desktop/Papers/git_hub/sum_sam.Rmd')

#This must be left uncommented if we want to show the content of the Markdown file once "Knit with Parameters" is pressed.
knitr::opts_chunk$set(echo = TRUE)

Say now I would like a chunk that will execute only if machine = SAM. How can I do that?

Was thinking about something like:

{r pressure, echo=FALSE, eval=params$machine}
plot(pressure)

but does not work

Thank you,

Federico

CodePudding user response:

Let there be a file called foo.Rmd with this content:

---
title: "SUM and SAM"
output: html_document
params:
  machine:
    input: select
    choices: [SUM, SAM]
    value: SUM
---

  
```{r, eval = params$machine == "SAM", echo=FALSE}
print("SAM was chosen")
```

```{r, eval = params$machine == "SUM", echo=FALSE}
print("SUM was chosen")
```

Then you can do:

rmarkdown::render("foo.Rmd", params = list(machine = "SAM"))

Alternativeley, there is the option knit with parameters in RStudio:

enter image description here

Resulting in foo.html:

enter image description here

  •  Tags:  
  • Related