本文介绍了使用 Shiny app 和 Rmarkdown 生成报告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个闪亮的应用程序,让您可以下载报告.现在我试图让事情变得超级简单,闪亮的应用程序上唯一的输入是用户可以使用 textarea
输入的一些文本:
I would like to create a shiny app that allows you to download a report. Right now I'm trying to keep things super simple and the only input on the shiny app is some text that the user can input using textarea
:
library(shiny)
server <- function(input, output) {
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')
# temporarily switch to the temp dir, in case you do not have write
# permission to the current working directory
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)
}
)
}
ui <- fluidPage(
tags$textarea(id="text", rows=10, cols=80, "Default value"),
flowLayout(radioButtons('format', 'Document format', c('HTML', 'Word'),
inline = TRUE),
downloadButton('downloadReport'))
)
shinyApp(ui = ui, server = server)
我的 report.Rmd
文件只有两行:
My report.Rmd
file only has two lines:
# Title
`r renderPrint({ input$text })`
唉,报告没有打印input$text
.
推荐答案
library(shiny)
server <- function(input, output) {
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')
# temporarily switch to the temp dir, in case you do not have write
# permission to the current working directory
owd <- setwd(tempdir())
on.exit(setwd(owd))
file.copy(src, 'report.Rmd', overwrite = TRUE)
out <- rmarkdown::render('report.Rmd',
params = list(text = input$text),
switch(input$format,
PDF = pdf_document(),
HTML = html_document(),
Word = word_document()
))
file.rename(out, file)
}
)
}
ui <- fluidPage(
tags$textarea(id="text", rows=20, cols=155,
placeholder="Some placeholder text"),
flowLayout(radioButtons('format', 'Document format', c('HTML', 'Word'),
inline = TRUE),
downloadButton('downloadReport'))
)
shinyApp(ui = ui, server = server)
和report.Rmd
---
title: "Parameterized Report for Shiny"
output: html_document
params:
text: 'NULL'
---
# Some title
`r params[["text"]]`
这篇关于使用 Shiny app 和 Rmarkdown 生成报告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!