R Shiny: keep old output

前端 未结 1 1433
逝去的感伤
逝去的感伤 2021-01-16 03:50

In a Shiny app, is there a way to keep old reactive output and display it in the app along with new reactive output? To provide an example: say I want to display the summary

相关标签:
1条回答
  • 2021-01-16 04:55

    Here's an approach that works. It uses a reactiveValues object, and each time you click the "Fit Model" button, it appends the new model to the end of the list. The numeric input controls how many models to display on the screen. This preserves every model you fit in the session.

    I didn't do the stargazer table because I'm not that familiar with it. But you should be able to adapt this pretty easily.

    library(shiny)
    library(broom)
    
    shinyApp(
      ui = 
        shinyUI(
          fluidPage(
            sidebarLayout(
              sidebarPanel(
                checkboxGroupInput(inputId = "indep",
                                   label = "Independent Variables",
                                   choices = names(mtcars)[-1],
                                   selected = NULL),
                actionButton(inputId = "fit_model",
                             label = "Fit Model"),
                numericInput(inputId = "model_to_show",
                             label = "Show N most recent models",
                             value = 2)
              ),
              mainPanel(
                htmlOutput("model_record")
              )
            )
          )
        ),
    
      server = 
        shinyServer(function(input, output, session){
          Model <- reactiveValues(
            Record = list()
          )
    
          observeEvent(
            input[["fit_model"]],
            {
              fit <- 
                lm(mpg ~ ., 
                   data = mtcars[c("mpg", input[["indep"]])])
    
              Model$Record <- c(Model$Record, list(fit))
            }
          )
    
          output$model_record <- 
            renderText({
              tail(Model$Record, input[["model_to_show"]]) %>%
                lapply(tidy) %>%
                lapply(knitr::kable,
                       format = "html") %>%
                lapply(as.character) %>%
                unlist() %>%
                paste0(collapse = "<br/><br/>")
            })
    
        })
    )
    
    0 讨论(0)
提交回复
热议问题