在闪亮的如何创建DT表中,我可以在其中同时添加行和删除行

时间:2018-08-24 11:11:04

标签: shiny dt

我已经尝试了不同的方法并完成了一项添加或删除任务。但是我无法在其中获得完整的解决方案,我可能在某处缺少一些小概念。我正在添加代码,请帮助我完成了我的基本应用。

library(shiny)
library(DT)
x<- data.frame(v1 = NA,
         v2 = NA

),
ui = shinyUI(
 fluidPage(
  sidebarLayout(
    sidebarPanel(
      textInput("v1","v1","a"),
      numericInput("V2","V2","1"),
      # Row selection
      numericInput(inputId = "row.selection", label = "Select row to be 
 deleted", min = 1, max = 100, value = "")
      # Add button
      actionButton(inputId = "add.button", label = "Add", icon = 
 icon("plus")), 
      # Delete button 
      actionButton(inputId = "delete.button", label = "Delete", icon = 
 icon("minus")),

    ),
    mainPanel(
      dataTableOutput('table')
    )
  )
 )
),

服务器端代码

server = function(input, output, session) {
  values <- reactiveValues()
  values$df <- x

  newEntry <- observe({
    cat("newEntry\n")
    if(input$add.button > 0) {
      newRow <- data.frame(input$v1, input$v2)
      isolate(values$df <- rbind(values$df,newRow))
   }
  })

  deleteEntry <- observe({
   cat("deleteEntry\n")
   if(input$delete.button > 0) {
     if(is.na(isolate(input$row.selection))){
       values$df <- isolate(values$df[-nrow(values$df), ])
     } else {
       values$df <- isolate(values$df[-input$row.selection, ])
     }
   } 

  })

  output$table = renderDataTable({
    values$df 

  })

}

1 个答案:

答案 0 :(得分:0)

尝试使用observeEvent,而不是使用带actionbutton的obser 而且,您在输入$ v2中遇到大小写问题(应输入$ V2) 试试修改后的代码:

library(shiny)
library(DT)
x<- data.frame(v1 = NA,
               v2 = NA

)
ui = shinyUI(
  fluidPage(
    sidebarLayout(
      sidebarPanel(
        textInput("v1","v1","a"),
        numericInput("V2","V2","1"),
        # Row selection
        numericInput(inputId = "row.selection", label = "Select row to be 
                     deleted", min = 1, max = 100, value = ""),
        # Add button
        actionButton(inputId = "add.button", label = "Add", icon = 
                       icon("plus")), 
        # Delete button 
        actionButton(inputId = "delete.button", label = "Delete", icon = 
                       icon("minus"))

        ),
      mainPanel(
        dataTableOutput('table')
      )
    )
  )
)
server = function(input, output, session) {
  values <- reactiveValues()
  values$df <- x

  observeEvent(input$add.button,{
    cat("addEntry\n")
    print(input$v1)
    print(input$V2)
    newRow <- data.frame(input$v1, input$V2)
    colnames(newRow)<-colnames(values$df)
    values$df <- rbind(values$df,newRow)
    print(nrow(values$df))
  })

  observeEvent(input$delete.button,{
    cat("deleteEntry\n")
    if(is.na(input$row.selection)){
      values$df <- values$df[-nrow(values$df), ]
    } else {
      values$df <- values$df[-input$row.selection, ]
    }
  })  

  output$table = renderDataTable({
    values$df 
  })

}
shinyApp(ui,server)

只需运行上面的所有代码,它就可以正常工作。