AntoineSoetewey / statsandr

A blog on statistics and R aiming at helping academics and professionals working with data to grasp important concepts in statistics and to apply them in R. See www.statsandr.com
http://statsandr.com/
35 stars 15 forks source link

Generate PDF and WORD from this code #5

Closed JovaniSouza closed 4 years ago

JovaniSouza commented 4 years ago
library(shinyBS)
library(shiny)
library(rmarkdown)
library(knitr)

ui <- bootstrapPage(
  navbarPage(theme = shinytheme("flatly"), collapsible = TRUE,
             "TEST", 

  tabPanel("First page",
  sidebarLayout(
    sidebarPanel(

      sliderInput("bins1",
                  "Number of bins:",
                  min = 1,
                  max = 30,
                  value = 10),
      radioButtons("format", "Download report:", c("PDF", "Word"),
                   inline = TRUE),
      downloadButton("downloadReport"),

    ),

    mainPanel(
      plotOutput("distPlot1")
    ))),

  tabPanel("Second page",
           sidebarLayout(
             sidebarPanel(

               sliderInput("bins2",
                           "Number of bins:",
                           min = 1,
                           max = 30,
                           value = 10),
             ),

             mainPanel(
               plotOutput("distPlot2")

  )))))

server <- function(input, output) {

  output$distPlot1 <- renderPlot({
    x    <- faithful[, 2]
    bins1 <- seq(min(x), max(x), length.out = input$bins1 + 1)

    hist(x, breaks = bins1, col = 'darkgray', border = 'white')
  })

  output$distPlot2 <- renderPlot({
    x    <- faithful[, 2]
    bins2 <- seq(min(x), max(x), length.out = input$bins2 + 1)

    hist(x, breaks = bins2, col = 'darkgray', border = 'white')
  })

  output$downloadReport <- downloadHandler(
    filename = function() {
      paste("my-report", sep = ".", switch(
        input$format, PDF = "pdf", Word = "docx"
      ))
    },

    content = function(file) {
      src <- normalizePath("report.Rmd")

      owd <- setwd(tempdir())
      on.exit(setwd(owd))
      file.copy(src, "report.Rmd", overwrite = TRUE)

      library(rmarkdown)
      out <- render("report.Rmd", switch(
        input$format,
        PDF = pdf_document(), Word = word_document()
      ))
      file.rename(out, file)
    }
  )
}

# Run the application
shinyApp(ui = ui, server = server)
JovaniSouza commented 4 years ago

I want to make a report in PDF or Word, contemplating the output$distPlot1 as the output$distPlot2. But when I press the Download button it doesn't work. Could you help me with this question please?

AntoineSoetewey commented 4 years ago

As you can see in https://antoinesoetewey.shinyapps.io/statistics-202/ it’s possible to generate word and PDF reports.

See the files app.R and report.Rmd of this repo: https://github.com/AntoineSoetewey/statistics-202