Search code examples
rshinyr-markdownshinyappsshiny-reactivity

How to run scripts by selecting them from a dropdown menu in R Shiny app?


I am trying to create a shiny app where the user selects an R Markdown file from a drop down menu, and that file is then rendered in the app and the output of that file, a pdf file pops up.

I don't have trouble making a drop down menu, but I am struggling with how to code all of that in the server side of the script.

How would I be able to get a Shiny app to render an R markdown file from a drop down menu? Any help is appreciated.


Solution

  • As discussed in comments:

    library(shiny)
    shinyApp(
      ui = fluidPage(
        selectInput("report", "Report", choices=c('Report1.Rmd','Report2.Rmd')),
        downloadButton("report", "Generate report")
      ),
      server = function(input, output) {
        output$report <- downloadHandler(
          # For PDF output, change this to "report.pdf"
          filename = "report.html",
          content = function(file) {
            # Set up parameters to pass to Rmd document
            params <- list(n = 1)
            
            rmarkdown::render(input$report, output_file = file,
                              params = params,
                              envir = new.env(parent = globalenv())
            )
          }
        )
      }
    )
    

    The .Rmd files should be in the working directory.

    For example: Report1.Rmd

    title: "Dynamic report 1"
    output: html_document
    params:
      n: NA
    ---
    
    ```{r}
    # The `params` object is available in the document.
    params$n
    ```
    
    A plot1 of `params$n` random points.
    
    ```{r}
    plot(rnorm(params$n), rnorm(params$n))
    ```