在renderPlot和下载处理程序中使用反应式表达式

时间:2014-06-11 08:21:47

标签: r render shiny

我在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)
}

1 个答案:

答案 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