我想生成一个包含来自另一个模块的绘图的报告,但我的代码不起作用。
我检查了其他闪亮开发人员的一些示例,但我的代码不起作用。
据我了解,我需要:
(1) 返回绘图
plot module
(2) 将其传递给
download server
(3)也需要将其包含在
main server
中(我不明白这里的逻辑,我需要你的帮助解释)
我的最小例子:
# Module 1,
plot_ui <- function(id) {
ns <- NS(id)
tagList(
plotOutput(ns("plot"))
)
}
plot_server <- function(id) {
moduleServer(id, function(input, output, session) {
myplot <- reactive({plot(x = mtcars$wt, y = mtcars$mpg)})
output$plot <-renderPlot({
myplot()
})
return(myplot)
})
}
# Module 2
download_ui <- function(id) {
ns <- NS(id)
tagList(
downloadButton(outputId = ns("report_button"),
label = "Generate report"
)
)
}
download_server <- function(id, myplot) {
moduleServer(id, function(input, output, session){
output$report_button<- downloadHandler(
filename = "report.html",
content = function(file) {
tempReport <- file.path(tempdir(), "myRport.Rmd")
file.copy("myReport.Rmd", tempReport, overwrite = TRUE)
params <- list(plot1 = myplot())
rmarkdown::render(tempReport,
output_file = file,
params = params
)
}
)
}
)
}
# Application
library(shiny)
app_ui <- function() {
fluidPage(
plot_ui("plot_ui_1"),
download_ui("download_ui_2")
)
}
app_server <- function(input, output, session) {
getPlot <- plot_server("plot_ui_1")
download_server("download_ui_2", myplot = getPlot)
}
shinyApp(app_ui, app_server)
我的 Markdown 文件
---
title: "Test"
output: html_document
params:
plot1: NA
---
```{r}
params$plot1
```
基本上你已经做对了一切。但是,为了使您的代码正常工作,您必须通过将
envir = new.env(parent = globalenv())
添加到 rmarkdown::render
来在新环境中渲染 Rmd。参见例如生成可下载的报告。此外,TBMK 您无法通过 params
将基本 R 图传递给 Rmd,即,当您的代码工作时,渲染报告中不会显示任何图。这就是为什么我切换到ggplot2
:
# Module 1,
plot_ui <- function(id) {
ns <- NS(id)
tagList(
plotOutput(ns("plot"))
)
}
plot_server <- function(id) {
moduleServer(id, function(input, output, session) {
myplot <- reactive({
#plot(x = mtcars$wt, y = mtcars$mpg)
ggplot(mtcars, aes(wt, mpg)) +
geom_point()
})
output$plot <-renderPlot({
myplot()
})
return(myplot)
})
}
# Module 2
download_ui <- function(id) {
ns <- NS(id)
tagList(
downloadButton(outputId = ns("report_button"),
label = "Generate report"
)
)
}
download_server <- function(id, myplot) {
moduleServer(id, function(input, output, session){
output$report_button<- downloadHandler(
filename = "report.html",
content = function(file) {
tempReport <- file.path(tempdir(), "myRport.Rmd")
file.copy("myReport.Rmd", tempReport, overwrite = TRUE)
params <- list(plot1 = myplot())
rmarkdown::render(tempReport,
output_file = file,
params = params,
envir = new.env(parent = globalenv())
)
}
)
}
)
}
# Application
library(shiny)
library(ggplot2)
app_ui <- function() {
fluidPage(
plot_ui("plot_ui_1"),
download_ui("download_ui_2")
)
}
app_server <- function(input, output, session) {
getPlot <- plot_server("plot_ui_1")
download_server("download_ui_2", myplot = getPlot)
}
shinyApp(app_ui, app_server)