【问题标题】:Shiny: Save value box outputs in vectorShiny:将值框输出保存在向量中
【发布时间】:2021-06-19 09:05:39
【问题描述】:

我在 Shiny 仪表板中有一个值框,它正在使用 ReactivePoll 功能进行自我更新。该值来自 SQL 查询。

我需要在更新时保存每个值(当数据库中有新记录时会发生这种情况),我会将这些值保存在向量中。因此,每当我们在值框中有一个新值时,这个向量的长度就会增加。

最后,我想用这个向量创建一个 line char。

我应该使用哪个 Shiny 函数?

谢谢!

【问题讨论】:

    标签: r function shiny shinydashboard reactive


    【解决方案1】:

    当然。我们可以将值存储在reactiveValues 中的向量中,这样我们就可以从任何地方更新和访问它。

    添加到向量就像myvector <- c(myvector, mynewvalue) 一样简单。

    下面是一个最小的工作示例。它显示了向向量添加值并在 valueBoxes 和绘图中显示该向量。为简单起见,我们将跳过 reactivePoll 部分。

    library(shiny)
    library(shinydashboard)
    
    ui <- dashboardPage(
    
        dashboardHeader(),
        dashboardSidebar(),
        dashboardBody(
        
            valueBoxOutput("myvaluebox_latest"),
            valueBoxOutput("myvaluebox_all"),
            
            numericInput("mynumericinput", "Enter a Value", min = 1, max = 10, value = 5),
            actionButton("myactionbutton", label = "Add to Value to Vector"),
            
            plotOutput("myplot")
    
        )
        
    )
    
    server <- function(input, output, session) {
     
        #Create a reactive to store our vector
        myreactives <- reactiveValues(
            
            myvector = NULL
            
        )
        
        #Runs when the button is pressed
        observeEvent(input$myactionbutton, {
            
            #Add the selected value to our vector
            myreactives$myvector <- c(myreactives$myvector, input$mynumericinput)
            
        })
        
        #Generate the valuebox for the latest data, runs when the vector changes
        output$myvaluebox_latest <- renderValueBox(
    
            valueBox(value = tail(myreactives$myvector, 1), subtitle = "Latest Value"),
    
        )
        
        #Generate the valuebox for the all the data, runs when the vector changes
        output$myvaluebox_all <- renderValueBox(
    
            valueBox(value = paste(myreactives$myvector, collapse = " "), subtitle = "All Values")
    
        )
        
        #Generate the plot
        output$myplot <- renderPlot({
            
            #Don't draw the plot when there is no data in the vector yet
            req(myreactives$myvector)
            
            plot(myreactives$myvector, type = "l")
            
        })
        
    }
    
    shinyApp(ui, server)
    

    【讨论】:

    • mi ValueBox 的值是一个反应式表达式,当数据库中有新记录时,它只执行 SQL 查询。我可以使用 ObserveEvent 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-10
    • 2021-10-10
    相关资源
    最近更新 更多