当然。我们可以将值存储在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)