【发布时间】:2018-04-05 04:48:55
【问题描述】:
我创建了一个相当长且复杂的闪亮应用程序,它根据各种用户输入生成表格和绘图。我想创建一个“下载报告”按钮,该按钮将显示应用程序上当前可见的图表。
但是,我似乎无法生成有效的报告。我使用了一个包含我的问题的示例闪亮应用程序,希望有一个简单的解决方案。当我点击“下载报告”时,它会要求我选择保存位置并生成一个名为“报告”的报告。但是,它不是 HTML 格式。它实际上没有任何格式,所以我无法打开它并查看结果
闪亮的应用:
#install.packages("shiny")
library(shiny)
library(ggplot2)
ui <- fluidPage(
title = 'Example application',
sidebarLayout(
sidebarPanel(
helpText(),
selectInput('x', 'Build a regression model of mpg against:',
choices = names(mtcars)[-1]),
radioButtons('format', 'Document format', c('PDF', 'HTML', 'Word'),
inline = TRUE),
downloadButton('downloadReport')
),
mainPanel(
plotOutput('regPlot')
)
)
)
server <- function(input, output) {
chart1 <- reactive({
ggplot(data = mtcars, aes(x=input$x, y=mpg))+geom_point()
})
output$regPlot <- renderPlot({
chart1()
})
output$downloadReport <- downloadHandler(
filename = function() {
paste('my-report', sep = '.', switch(
input$format, PDF = 'pdf', HTML = 'html', 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(), HTML = html_document(), Word = word_document()
))
file.rename(out, file)
}
)
}
shinyApp(ui=ui, server=server)
R Markdown 文件:
---
title: "Download report"
author: "Test"
date: "24 October 2017"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(ggplot2)
library(shiny)
library(rmarkdown)
```
## Output plot
Should output plot, here:
```{r test plot, echo=FALSE}
chart1()
```
我一定是遗漏了一些简单的东西!
【问题讨论】:
-
我不知道我在这上面浪费了多少时间。我知道这很简单。谢谢!!!
-
您似乎回复了一条已删除的评论。出了什么问题?
-
添加了解决问题的答案:)
标签: html r shiny report r-markdown