Chechy Levas
Chechy Levas

Reputation: 2312

R Shiny - How can I dynamically add to a table without using global variables?

How can I achieve the same functionality as the below example, without using global variables. I suspect the answer might have something to do with the 'reactiveValues()' function but I can't get it to work.

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)

Upvotes: 1

Views: 234

Answers (1)

Florian
Florian

Reputation: 25375

Your suggestion of reactiveValues is a good one, however since we only want to hold one variable (the data.frame), we can also use reactiveVal. All we require next to that is an observeEvent that listens to the button click. Working example:

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)

Hope this helps!

Upvotes: 1

Related Questions