How to render multiple output from the same analysis without executing it multiple time? (Shiny)

后端 未结 1 451
借酒劲吻你
借酒劲吻你 2021-01-07 04:58

I am writing an shiny app in which contains an stochastic function generates four objects - one plot and three tables. However, I want to render each object in different tab

相关标签:
1条回答
  • 2021-01-07 05:23

    If your model() is a list and contains data for all tables and a plot, it should work as in my example.

    In this app, after pressing a button, a random number and data for a table and a plot are generated. Then the number, data for table and a plot are returned as a list and rendered with appropriate render* functions.

    This app illustrates that the model function won't be re-run after accessing it with model() in other reactive functions.

    However, there is an odd thing...the plot is not always rendered. You sometimes have to click the button few times to get the plot. The table is working always.


    library(shiny)
    
    ui <- shinyUI(fluidPage(
       br(),
       actionButton("numb", "generate a random numbers"),
       br(),
       br(),
       verbatimTextOutput("text"),
       plotOutput("plot"),
       tableOutput("table")
    ))
    
    server <- shinyServer(function(input, output) {
    
      model <- eventReactive(input$numb, {
        # draw a random number and print it
        random <- sample(1:100, 1)
        print(paste0("The number is: ", random))
    
        # generate data for a table and plot
        data <- rnorm(10, mean = 100)
        table <- matrix(data, ncol = 2)
    
        # create a plot 
        Plot <- plot(1:length(data), data, pch = 16, xlab ="", ylab = "")
    
        # return all object as a list
        list(random = random, Plot = Plot, table = table)
      })
    
       output$text <- renderText({
         # print the random number after accessing "model" with brackets.
         # It doesn't re-run the function.
         youget <- paste0("After using model()$random you get: ", model()$random,
                          ". Compare it with a value in the console")
         print(youget)
         youget
       })
    
       output$plot <- renderPlot({
         # render saved plot
         model()$Plot
       })
    
       output$table <- renderTable({
    
         model()$table
       })
    })
    
    
    shinyApp(ui = ui, server = server)
    
    0 讨论(0)
提交回复
热议问题