简体   繁体   中英

Append to end of dataframe and display as table in Shiny app

I am trying to create a very simple app where users can enter a text field and a number, which is appended to a dataframe, and the dataframe is then displayed as a table. I am 99% of the way there, but the only problem is that new entries are overwriting the old entries, so you only ever get one row in the data frame and one row in the displayed table.

Here is a reproducible example:


library(shiny)
library(DT)

shinyApp(
    ui = navbarPage("Making a dataframe and displaying it",
                    tabPanel("Input",
                             
                             mainPanel(
                                 textInput("text", "Text input", ""),
                                 numericInput("number", "Numeric input", min=1, value = 1),
                                 actionButton("submit", "Submit")
                             )
                             
                    ),
                    tabPanel("The list",
                             DT::dataTableOutput("thelist")
                    )
    ),
    
    server = function(input, output) {
        
        initial <- data.frame("text" = character(), "number" = numeric())
        
        thelist <- eventReactive(input$submit,{rbind(initial,
                             data.frame("text" = input$text, "number" = input$number))
        })
        
        output$thelist = renderDataTable(thelist())
        
    }
)

Thanks!

You can put the dataframe in reactiveValues and use observeEvent to add a new row on click.

library(shiny)
library(DT)

shinyApp(
  ui = navbarPage("Making a dataframe and displaying it",
                  tabPanel("Input",
                           mainPanel(
                             textInput("text", "Text input", ""),
                             numericInput("number", "Numeric input", min=1, value = 1),
                             actionButton("submit", "Submit")
                           )
                           
                  ),
                  tabPanel("The list",
                           DT::dataTableOutput("thelist")
                  )
  ),
  
  server = function(input, output) {
    
    rv <- reactiveValues(data = data.frame(text = character(), number = numeric()))
    
    observeEvent(input$submit,{
      rv$data <- rbind(rv$data, data.frame(text = input$text, number = input$number))
    })
    
    output$thelist = renderDataTable({
      rv$data
      })
    
  }
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM