在renderPrint和renderPlot之间共享对象

时间:2019-07-05 11:20:49

标签: r shiny

在以下示例中,R对象fit是在shiny::renderPrint中创建的,而不是在renderPlot中创建的。因此,为print()完成了绘制,但没有为plot()完成。 在实际阶段,fit是由rstan:sampling()生成的拟合模型对象,它花费很长时间,因此在renderPrintrenderPlot中我都不会执行两次。有什么主意吗?我是Shiny的初学者。

    library(shiny)

ui <- fluidPage(  
         mainPanel(
            shiny::sliderInput("aaa",
                               "aaa:",
                               min = 1, max = 11111, value = 5),

            shiny::plotOutput("plot"),
            shiny::verbatimTextOutput("print")       )
    )


     server <- function(input, output) {
        output$print <- shiny::renderPrint({
            fit <- input$aaa*100 # First creation of object, 
                                 # and we use it in the renderPlot.
                                 # So, we have to create it twice even if it is exactly same??
                                 # If possible, I won't create it 
                                 # In the renderPlot, twice.
            print(fit)
        })



        output$plot <- shiny::renderPlot({

          # The fit is again created
          # If time to create fit is very long, then total time is very heavy.
          # If possible, I do not want to make fit again.

           fit <- input$aaa*100  #<- Redundant code or I want to remove it.

           plot(1:fit)
        })
    }

     shinyApp(ui = ui, server = server)

修改

为避免生成对象的重复代码,我使用以下代码,然后运行良好。谢谢@bretauv。

library(shiny)

ui <- fluidPage(

    mainPanel(
        shiny::sliderInput("aaa",
                           "aaa:",
                           min = 1, max = 11111, value = 5),

        shiny::plotOutput("plot"),
        shiny::verbatimTextOutput("print")       )
)


server <- function(input, output) {

##########     Avoid duplicate process             ###################
    test <- reactive({input$aaa*100})
#####################################################################    


    output$print <- shiny::renderPrint({
      #  fit <- input$aaa*100  # No longer required 
        print(test())
    })



    output$plot <- shiny::renderPlot({
       # fit <- input$aaa*100  # No longer required 

        plot(1:test())
    })
}

shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:1)

如果不想重复fit,请尝试将fit表达式放入反应函数中,例如:test <- reactive({input$aaa*100}),然后在output函数中使用{ {1}}