【问题标题】:Add values to a reactive table in shiny在闪亮的反应表中添加值
【发布时间】:2014-06-07 20:27:02
【问题描述】:

我希望我闪亮的应用程序的用户能够迭代地将元素添加到表中,但我不知道如何保存这些值。

在这个例子中,我希望用户能够在文本框中添加值,这些值应该被添加到主面板中表格的底部。目前,之前添加的值都丢失了。

library(shiny)

runApp(list(
  ui=pageWithSidebar(headerPanel("Adding entries to table"),
                     sidebarPanel(textInput("text1", "Column 1"),
                                  textInput("text2", "Column 2"),
                                  actionButton("update", "Update Table")),
                     mainPanel(tableOutput("table1"))),
  server=function(input, output, session) {
    tableStart <- data.frame(Column1 = NA, Column2 = NA)
    newEntry <- reactive({
      input$update
      newLine <- isolate(c(input$text1, input$text2))
      })
    output$table1 <- renderTable({rbind(tableStart, newEntry())})
  }))

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    我认为您想使用reactiveValues() 来存储您的数据框。这是一个可能的解决方案:

    library(shiny)
    
    runApp(list(
      ui=pageWithSidebar(headerPanel("Adding entries to table"),
                     sidebarPanel(textInput("text1", "Column 1"),
                                  textInput("text2", "Column 2"),
                                  actionButton("update", "Update Table")),
                     mainPanel(tableOutput("table1"))),
    server=function(input, output, session) {
    values <- reactiveValues()
    values$df <- data.frame(Column1 = NA, Column2 = NA)
    newEntry <- observe({
      if(input$update > 0) {
        newLine <- isolate(c(input$text1, input$text2))
        isolate(values$df <- rbind(values$df, newLine))
      }
    })
    output$table1 <- renderTable({values$df})
    }))
    

    编辑

    为避免创建空行,请创建一个空的 data.frame 而不是 NA

    values$df <- data.frame(Column1 = numeric(0), Column2 = numeric(0))
    

    对于添加行,索引似乎比 rbind() 更好(这会弄乱列名......不知道为什么):

    isolate(values$df[nrow(values$df) + 1,] <- c(input$text1, input$text2))
    

    【讨论】:

    • 我想尝试其他的添加。但它没有用。 stackoverflow.com/questions/34707097/…
    • dplyr::bind_rows() 可以很好地保留列名,顺便说一句:isolate(values$df &lt;- dplyr::bind_rows(values$df, newLine))
    • 为什么不使用observeEvent?它会自动隔离第二个参数中的代码吗? observeEvent({(input$update) { newLine &lt;- c(input$text1, input$text2) values$df &lt;- rbind(values$df, newLine) } })
    猜你喜欢
    • 2017-07-27
    • 2020-04-11
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    相关资源
    最近更新 更多