如何在Shiny选项卡中输出RMarkdown文件(使用params运行)

时间:2018-02-18 14:33:35

标签: shiny r-markdown

我想在Shiny标签中显示RMarkdown文件。问题是它只有在没有明确传递给RMarkdown文件的参数时才有效。随附的文件对应一个Shiny应用程序,该应用程序有2个选项卡:一个带有下载按钮(按预期工作),另一个显示RMarkdown报告的输出(但没有参数)

你知道怎么做吗?

接下来有2个文件嵌入。数据文件是常见的iris.csv。

闪亮的应用代码(shinyMinimal.R):

library(rmarkdown)
library(shiny)

thisUI <- shinyUI(
  fluidPage(
    mainPanel(
      tabsetPanel(
        tabPanel("Report in webpage",
           includeMarkdown("minimalReport.Rmd")
        ),
        tabPanel("Download report",
          flowLayout(
            radioButtons('format', 'Document format', c('HTML', 'Word', 'PDF'),inline = TRUE
           ),
        downloadButton(outputId = "downloadReport", label  = "Download the report")
          )
        )
      )
    )
  )
)
thisServer <-  function(input, output) {
   output$downloadReport <- downloadHandler(
     filename = function() {
       switch(
         input$format, 
         PDF =  base::paste('minimalReport', sep = '.','pdf'), 
         HTML = base::paste('minimalReport', sep = '.','html'),
         Word = base::paste('minimalReport', sep = '.','docx')
       )
    },
    content = function(nameOutputFile) {
      nameInputThisFile <- "iris.csv"
      paramsReportTwo <- list(n = 64, nameInputFile = nameInputThisFile)
      inputRmdFile <- "minimalReport.Rmd"

      rmarkdown::render(input = inputRmdFile,
                    params = paramsReportTwo,
                    output_file = nameOutputFile,
                    switch(input$format,
                           PDF = pdf_document(), 
                           HTML = html_document(), 
                           Word = word_document()
                    )
      )
     }
    )  
  }

 shiny::shinyApp(ui = thisUI, server = thisServer)

第二个是RMarkdown报告(minimalReport.R)

---
title: "Dynamic report"
output: html_document
params:
  n: NA
  nameInputFile: NA
---

There is some text.

```{r}
# The `params` object is available in the document.
params$n
```

A plot of `r params$n` random points.

```{r}
plot(rnorm(params$n), rnorm(params$n))
```
Read from a file
```{r}
inputData <- readr::read_csv(params$nameInputFile)
```
The mean of first data column from file `r params$nameInputFile` is `r mean(inputData[[1]])`

And then show a table
```{r}
head(inputData)
```
The End

0 个答案:

没有答案