How to add multiple rows to a dataframe in Shiny

Viewed 25

I want to create a data frame where the user can click an "add" button to add a row. It's important though that I can use the button any number of times I want to add as many rows to the dataframe as I want. I've tried this

library(shiny)

ui <- fluidPage(
    numericInput("a", "a", 1),
    actionButton("add", "add"),
    tableOutput("sum")
    
)


server <- function(input, output, session) {
    
    dat<-eventReactive(input$add, {
        dat<-data.frame(
            col=c(input$a)
        )})
    
    output$sum<-renderTable(dat())
    
}

shinyApp(ui, server)

And that almost works but I can only add one element to the data frame. When I try to click the "add" button again the value in the data frame just gets replaced with the new value, instead of both of them being in stored.

Where am I going wrong here?

1 Answers

One option to achieve your desired result would be to make your dat a reactiveVal and to use an obeserveEvent to add the rows using e.g. tibble::add_row:

library(shiny)
library(tibble)

ui <- fluidPage(
  numericInput("a", "a", 1),
  actionButton("add", "add"),
  tableOutput("sum")
  
)

server <- function(input, output, session) {
  dat <- reactiveVal(tibble(col = numeric(0)))
  
  observeEvent(input$add, {
    dat(tibble::add_row(dat(), col = input$a))  
  })
  
  output$sum <- renderTable(dat())
  
}

shinyApp(ui, server)

enter image description here

Related