Generating downloadable reports from Shiny app

You can use the params argument in the render function to pass the path of the dataset. In the Rmd you can use this param to read the csv. See below, I hope this helps.

library(shiny)
library(rmarkdown)

ui <- fluidPage(
  titlePanel("Uploading Files"),
  sidebarLayout(
    sidebarPanel(
      fileInput(
        inputId = "file1", label = "Choose CSV File",
        multiple = FALSE,
        accept = c("text/csv", "text/comma-separated-values,text/plain", ".csv")
      ),
      radioButtons("format", "Document format", c("PDF", "HTML", "Word"), inline = TRUE)
    ),
    mainPanel(
      tableOutput("contents"),
      downloadButton("downloadReport")
    )
  )
)


server <- function(input, output) {
  dataset <- reactive({
    req(input$file1)
    read.csv(file = input$file1$datapath,
             na.strings = ".", 
             sep = ";",
             header = TRUE,
             nrows=10)               
  })
  
  output$contents <- renderTable({
    req(dataset())
    head(dataset())
  })
  
  output$downloadReport <- downloadHandler(
    filename = function() {
      paste("my-report", sep = ".", switch(
        input$format, PDF = "pdf", HTML = "html", Word = "docx"
      ))
    },
    
    content = function(file) {
      src <- normalizePath("traitemant_bis.Rmd")
      
      owd <- setwd(tempdir())
      on.exit(setwd(owd))
      file.copy(src, "traitemant_bis.Rmd", overwrite = TRUE)
      
      out <- render("traitemant_bis.Rmd", switch(
        input$format,
        PDF = pdf_document(), HTML = html_document(), Word = word_document()),
        params = list(data = input$file1$datapath)
      )
      file.rename(out, file)
    }
  )
}

shinyApp(ui, server)

Rmd

---
title: "data param"
output: html_document
params:
  data: "test.csv"
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```


```{r data}
read.csv(file = params$data,
         na.strings = ".", 
         sep = ";",
         header = TRUE,
         nrows=10)
```
1 Like