如何在不使用全局变量的情况下实现与以下示例相同的功能。 我怀疑答案可能与'reactiveValues()'函数有关,但我不能让它起作用。
library(shiny)
library(DT)
ui <- fluidPage(
selectInput("selectMe", "Select Something", list(A="A",B="B",C="C",D="D",E="E")),
actionButton("pressMe", "Add Something"),
DT::dataTableOutput("theTable")
)
someThings <<- isolate(data.frame())
renderTable = function(input) {
DT::renderDataTable({
currentSelect = isolate(input$selectMe)
if (input$pressMe > 0) {
currentThings = someThings
newThings = rbind(currentThings, data.frame(SelectedThing = currentSelect))
someThings <<- isolate(newThings)
newThings
}
})
}
server <- function(input, output, session) {
output$theTable = renderTable(input)
}
shinyApp(ui, server)
答案 0 :(得分:1)
您对reactiveValues
的建议很好,但由于我们只想保留一个变量(data.frame
),我们也可以使用reactiveVal
。我们旁边要求的只是一个observeEvent
,它会监听按钮点击。工作示例:
library(shiny)
library(DT)
ui <- fluidPage(
selectInput("selectMe", "Select Something", list(A="A",B="B",C="C",D="D",E="E")),
actionButton("pressMe", "Add Something"),
DT::dataTableOutput("theTable")
)
server <- function(input, output, session) {
my_df <- reactiveVal(data.frame())
observeEvent(input$pressMe,ignoreNULL = T,ignoreInit = T, {
currentThings = my_df()
newThings = rbind(currentThings, data.frame(SelectedThing = input$selectMe))
my_df(newThings) # set the new value of the reactiveVal.
})
output$theTable = renderDataTable(my_df())
}
shinyApp(ui, server)
希望这有帮助!