【问题标题】:How to avoid code duplication in a render() function in Shiny for R如何避免 Shiny for R 中的 render() 函数中的代码重复
【发布时间】:2016-05-16 17:38:33
【问题描述】:

我是 Shiny 的新手,如果这是微不足道的,请原谅......

我有一个 server() 函数可以输出多个图。这些图使用相同的代码块,并且每个都添加了一些自己的代码,如下所示:

shinyServer( function( input, output ){
output$plot1 <- renderPlot({
  the block of the same code
  some code specific to plot1
})
output$plot1 <- renderPlot({
  The block of the same code
  some code specific to plot2
})

我想避免重复“相同代码的块”。这必须在 renderPlot 函数中,因为它从 UI 函数中获取可变数据。

【问题讨论】:

    标签: r function shiny


    【解决方案1】:

    您需要将块放入“反应式”中 - 就像一个函数,但它会对更改做出反应。

    shinyServer( function( input, output ){
      basicplot = reactive({
                     the block of the same code
                  })
    output$plot1 <- renderPlot({
      plot1 = basicplot()
      some code specific to plot1
    })
    output$plot2 <- renderPlot({
      plot2 = basicplot()
      some code specific to plot2
    })
    

    “basicplot”响应式基本上是一个函数,它输出 plot1 和 plot2 特定部分需要处理的任何内容。

    【讨论】:

    • 谢谢。我还听了有关反应的视频。正是我需要的。
    • 我要补充一点,如果basicplot 使用任何输入,您只需要使其反应。如果它独立于输入,那么它应该是一个传统的函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-23
    • 1970-01-01
    • 2023-03-14
    • 2021-10-16
    • 1970-01-01
    相关资源
    最近更新 更多