r语言 - 从Shiny app生成可下载的报告



我制作了一个R脚本,允许使用特定类型的数据集获得R Markdown报告。现在我希望其他人能够使用这个脚本,以便获得一个自动报告与他们的数据,但不使用这个脚本(特别是对于不掌握R的人)。

我尝试通过Shiny希望使一个接口,加载一个数据集,并会使我的脚本自动,但我不能使Shiny和我的Rmd之间的链接。

我如何告诉我的Rmd要处理的数据集不是我的Rmd脚本要在目录中查找的数据集,而是在Shiny界面上加载的数据集?

感谢这是闪亮的脚本与我的Rmd称为"traitemant_bis.Rmd":

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()
))
file.rename(out, file)
}
)
}
shinyApp(ui, server) ```

我将给出一个简单的示例来说明如何实现这一点。基本上,您可以将任何数据从shiny传递到Rmd作为params

如果你有多个数据帧或任何数据,将它们转换为单个列表并作为参数传递,你可以在RMarkdown

中提取单个数据应用程序。R

library(shiny)
ui <- fluidPage(
# Application title
titlePanel("RMD example"),

downloadButton("btn", "Generate Report")
)
# Define server logic required to draw a histogram
server <- function(input, output) {
data <- reactive({
mtcars
})


output$btn <- downloadHandler(

filename = function(){"myreport.docx"},
content = function(file) {

tempReport <- file.path(tempdir(),"markdown.Rmd")
file.copy("markdown.Rmd", tempReport, overwrite = TRUE)
rmarkdown::render("markdown.Rmd", output_format = "word_document", output_file = file,
params = list(table = data()), # here I'm passing data in params
envir = new.env(parent = globalenv()),clean=F,encoding="utf-8"
)


}
)
}
# Run the application 
shinyApp(ui = ui, server = server)

限制型心肌病文件

---
title: "Untitled"
author: "Mohan"
date: "2/17/2021"
params:
table: [some object]
output: word_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
params$table -> data
data
summary(data)
```

最新更新