我在renderPlot()
和downloadHandler()
中使用相同的反应表达式时遇到了问题。我想使用相同的反应表达式来减少以后的维护。我创建了两个创建非常简单的图形的例子(mwe1创建了一个你可以下载的jpeg,mwe2没有)。我更喜欢使用创意表达式的解决方案,该表达式可以由renderPlot()
和downloadHander()
使用,如mwe2。有人能帮我这个吗?
提前致谢!
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)
}
答案 0 :(得分:1)
将mwel2
更改为:
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)
plot(.hist())
dev.off()
}
)
}
)
runApp(app)
}
再次在plot
对象上调用.hist
。