I have had an issue by using the same reactive expression in renderPlot()
and in downloadHandler()
. I want to use the same reactive expression to minimize maintenance later. I have created two examples which create very simple figures (mwe1 creates a jpeg which you can download, mwe2 does not). I prefer a solution which uses a creative expression which can be both used by renderPlot()
and downloadHander()
as in mwe2. Is anybody able to help me with this?
Thanks in advance!
mwe1 <- function() {
app = list(
ui = bootstrapPage(
fluidPage(
sidebarPanel(
sliderInput("mean", "choose mean", -10, 10, 1),
sliderInput("sd", "choose sd", 0, 5, 1)),
mainPanel(
plotOutput("hist"),
downloadButton("histDownload")
)
)
),
server = function(input, output) {
output$hist <- renderPlot(hist(rnorm(1000, input$mean, input$sd)))
.hist <- reactive(hist(rnorm(1000, input$mean, input$sd)))
output$histDownload <- downloadHandler(
filename = function() {
paste("hist.jpg")
},
content = function(file) {
jpeg(file, quality = 100, width = 800, height = 800)
.hist()
dev.off()
}
)
}
)
runApp(app)
}
mwe2 <- function() {
app = list(
ui = bootstrapPage(
fluidPage(
sidebarPanel(
sliderInput("mean", "choose mean", -10, 10, 1),
sliderInput("sd", "choose sd", 0, 5, 1)),
mainPanel(
plotOutput("hist"),
downloadButton("histDownload")
)
)
),
server = function(input, output) {
output$hist <- renderPlot(.hist())
.hist <- reactive(hist(rnorm(1000, input$mean, input$sd)))
output$histDownload <- downloadHandler(
filename = function() {
paste("hist.jpg")
},
content = function(file) {
jpeg(file, quality = 100, width = 800, height = 800)
.hist()
dev.off()
}
)
}
)
runApp(app)
}
Change
mwel2
to:So call
plot
again on the.hist
object.